How to copy a DOM node with event listeners?

Chakradar Raju picture Chakradar Raju · Mar 14, 2013 · Viewed 28.2k times · Source

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.

Answer

Tim Down picture Tim Down · Mar 14, 2013

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.