Make event handler persisting after delete operation [ SOLVED ]

Is there way to bind event handler for click that persistent even if this situation happend:

structure
div1
 div2
   node

and now if only ,div2 and node, are deleted and again inserted into div1
is there some way to persistent event handler for this nesting

*tried this but doesn’t work
$(div1).on('click', 'div2 node', function....)

Is there some function that is watcher to this, and automatically attach these handlers?

EDIT:
actually this code
$(div1).on('click', 'div2 node', function....)
is ~same as @imtoobose answer
but when i tried my code i have wrong html structure not in javascript but staight in html…

On other hand u can see in @imtoobose how this $ code is maybe made under hood

I think you can’t do it in such a way. What does work: assign the event handler when you insert the elements.

Does this work before the elements are deleted? Delegation should be what you’re looking for, but I would have the delegate matcher be less specific, ie. ‘node’ instead of ‘div2 node’.

What if you do this:

document.getElementById('div1').addEventListener('click', function(e){
    if (e.target.id == 'div2') { do something }
});

This is obviously assuming you assign the appropriate ids to the divs. This should work, as long as you don’t remove div1.

1 Like

@PortableStick
do u think it is less efficient when i provide more specific selector, like i did?

@imtoobose
i’ll try, nice one

It’s not really about efficiency, I just wonder if the delegate selector is targeting the correct element. It’s really easy to be too specific with CSS selectors, and that can introduce bugs.

delegate selector targets correct elm

see update at the top