Javascript cloneNode with events

I am working on a greasemonkey script for gmail where I need to make a copy of the inbox link. Using cloneNode works fine, but I think there is an onclick event that is bound to it at runtime. So this is a two-part question: 1. Is there a way to see which events are associated with a node? 2. Is there a way to copy these events? The closest I found is jQuery, and I'm not ready to go there yet. Thank!

+1
source share
3 answers
  • Not if it is not set using the attribute onclickfor the element.
  • Not reliable (you can copy the attribute onclick, but whether it will continue to work depends on whether it was used and what it does).

You better add your own handler clickand then run this event on the original ... Or simulate the behavior in some other way.

+5
source

I think we can solve this problem with this theory:

We have a NodeList in JS, also called liveLists. We can check when their length changes, addEvent the desired common events for a new item in the list (length-1).

What they say ....

0
source

Nodelist .

<body>
        <div id="one" class="clones" style="background:red;width:100px;height:100px"></div>
    </body>

    <script>

        //Selecor based live list [Advantage]
        var nodeList = document.getElementsByClassName('clones')

        //Common Function for nodelist
        nodeList.addEvents = function(){
            nodeList.item(nodeList.length-1).addEventListener('click',function(){
                    console.log(this.id);
            });
        }
        nodeList.addEvents();

        //Making Clone
        var _clone  =  document.getElementsByTagName('div')[0].cloneNode(true);

        //Changing Id
        _clone.id="two"

        document.body.appendChild(_clone);
        nodeList.addEvents();
    </script>
0

Source: https://habr.com/ru/post/1768785/


All Articles