How to copy a DOM node with event listeners?
This does not answer the question exactly, but if the use case allows for moving the element rather than copying it, you can use removeChild together with appendChild which will preserve the event listeners. For example:
function relocateElementBySelector(elementSelector, destSelector) {
let element = document.querySelector(elementSelector);
let elementParent = element.parentElement;
let destElement = document.querySelector(destSelector);
elementParent.removeChild(element);
destElement.appendChild(element);
}
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'sclone()
method is able to copy a node with its event listeners, for example.