Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clone element with all its events

I'm cloning a textarea in a page but the cloned element doesn't have any event of the primary element, is there any way to clone all events in cloned element?

var dupNode = node.cloneNode(deep);
like image 753
ehsandotnet Avatar asked Jun 05 '13 11:06

ehsandotnet


People also ask

What is cloneNode?

cloneNode() The cloneNode() method of the Node interface returns a duplicate of the node on which this method was called. Its parameter controls if the subtree contained in a node is also cloned or not. Cloning a node copies all of its attributes and their values, including intrinsic (inline) listeners.

How do you clone in HTML?

The cloneNode() method creates a copy of a node, and returns the clone. The cloneNode() method clones all attributes and their values. Set the deep parameter to true if you also want to clone descendants (children).


1 Answers

You can maybe use getEventListeners on nodes? Don't know how the support is, or if it's only supported in the console?

function cloneMassive(node) {
    // Clone the node, don't clone the childNodes right now...
    var dupNode = node.cloneNode(false);
    var events = getEventListeners(node);

    for(var p in events) {
        // All events is in an array so iterate that array:
        events[p].forEach(function(ev) {
            // {listener: Function, useCapture: Boolean}
            dupNode.addEventListener(p, ev.listener, ev.useCapture);
        });
    }
    // Also do the same to all childNodes and append them.
    if (node.childNodes.length) {
        [].slice.call(node.childNodes).forEach(function(node) {
            dupNode.appendChild(cloneMassive(node));
        });
    }

    return dupNode;
}

var dupBody = cloneMassive(document.body);

But it seems that getEventListeners isn't really supported:

Get event listeners attached to node using addEventListener


If you need to copy all event properties on the node as well you will need a list of all, and then simply copy them over:

['onclick', 'onmouseover', '...'].forEach(function(method) {
    dupNode[method] = node[method];
});
like image 192
Andreas Louv Avatar answered Sep 27 '22 20:09

Andreas Louv