Make event handler persisting after delete operation [ SOLVED ]

Make event handler persisting after delete operation [ SOLVED ]
0

#1

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


#2

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


#3

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’.


#4

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.


#5

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

@imtoobose
i’ll try, nice one


#6

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.


#7

delegate selector targets correct elm


#8

see update at the top