Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML DOM node lost events

When I move some DOM nodes form one context to another, all some of the children nodes lost their event listeners.

HTML

<div><lots of deep nodes .../><div>
<div>
   <div>
     <div#newNode></div>
   </div>
</div>

JS

nodes = $('div').find('nodes')
$('#newNode').html(nodes)

After the moving... all the nodes moved lost their events.

Any thoughts?

like image 703
klebervirgilio Avatar asked Dec 06 '25 08:12

klebervirgilio


2 Answers

You are copying the html, it does not have any event information with it.

You want to use .clone(true)

$('.whatToCopy').clone(true).appendTo('#NewLocation');
like image 130
epascarello Avatar answered Dec 08 '25 22:12

epascarello


Reconstituting or copying the HTML makes brand new DOM elements that do not have any of the event listeners of the previous nodes (the elements are created from scratch just like the original HTML in the page created elements without event listeners). So, naturally, they won't have any of your jQuery event listeners on them unless you run new code to add event listeners to them.

If you want to move the nodes, you can just directly move the DOM elements to a different place in the DOM without using the HTML (and thus without making new DOM elements) so all the event listeners stay attached. For example to move them:

nodes = $('div').find('nodes');
$('#newNode').append(nodes);

If you want to copy the nodes with event listeners attached, then you can use .clone(true, true) which will clone the nodes with data and events and do a deep clone (including children):

nodes = $('div').find('nodes');
$('#newNode').append(nodes.clone(true, true));

See the jQuery reference for .clone() for more info.

like image 20
jfriend00 Avatar answered Dec 08 '25 21:12

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!