简体   繁体   中英

store event listeners from a dom element in javascript

Is it possible to store all event listeners from an element in order to retrieve it after cloning an element

//clone element makes event listeners stripped
var old_element=document.getElementById('dhtml_menu-1895');     
// var el= alleventlistenersfrom this element
var new_element = old_element.cloneNode(true);  
old_element.parentNode.replaceChild(new_element, old_element);  

 //some event actions 

 //give back original event listeners

I think the real solution to your problem is to bind your event to an element higher up on the DOM that way you don't have to dynamically bind events when elements are created.

So I'm assuming you have something like this:

<div class='parent'>
  <div class='element-to-replace'></div>
</div>

And you are changing out the .element-to-replace in your code somewhere, but you have event listeners on it like so:

document.querySelector('.element-to-replace').addEventListener('click', doSomething);

In that situation, you should bind to the parent element since it will never change and target your child element.

document.querySelector('.parent').addEventListener('click', function(evt) {
  if (evt.target.className.includes('element-to-replace'))
    doSomething();
});

You can do that or abstract out the creation of those new elements and place your event binding code in the function block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM