Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a DOM node with event listeners?

I tried

node.cloneNode(true); // deep copy 

It doesn't seem to copy the event listeners that I added using node.addEventListener("click", someFunc);.

We use the Dojo library.

like image 374
Chakradar Raju Avatar asked Mar 14 '13 11:03

Chakradar Raju


People also ask

How do I copy a DOM?

You can easily change the DOM without having to edit the HTML as a big piece of string. Right click on a node and select Copy. You can paste in your code editor, or for prototyping, you can paste the DOM node elsewhere in the DOM tree.

How do you find event listeners in a DOM node?

Right-click on the search icon button and choose “inspect” to open the Chrome developer tools. Once the dev tools are open, switch to the “Event Listeners” tab and you will see all the event listeners bound to the element. You can expand any event listener by clicking the right-pointing arrowhead.

How do I copy Nodejs to another node?

Right-click the node that you want to copy, and then click Copy. Right-click the Record node or group node into which you want to insert the copied node, and then click Paste.


1 Answers

cloneNode() does not copy event listeners. In fact, there's no way of getting hold of event listeners via the DOM once they've been attached, so your options are:

  • Add all the event listeners manually to your cloned node
  • Refactor your code to use event delegation so that all event handlers are attached to a node that contains both the original and the clone
  • Use a wrapper function around Node.addEventListener() to keep track of listeners added to each node. This is how jQuery's clone() method is able to copy a node with its event listeners, for example.
like image 132
Tim Down Avatar answered Oct 07 '22 10:10

Tim Down