HTML DOM NODE lost events

When I move some dom nodes, forming one context for another, all parts of the child nodes lose 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 moving ... all moved nodes have lost their events.

Any thoughts?

+3


source to share


3 answers


You are copying the html, it doesn't have any event information.

Do you want to use .clone(true)



$('.whatToCopy').clone(true).appendTo('#NewLocation');

      

+2


source


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

If you want to move nodes, you can simply move DOM elements to a different location in the DOM without using HTML (and thus without creating new DOM elements) so that all event listeners remain attached. For example, to move them:

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

      




If you want to copy nodes with event listeners enabled, you can use .clone(true, true)

which will clone nodes with data and events and deep clone (including children):

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

      

See jQuery link for.clone()

details .

+2


source


try using append or prepend on $('#newNode')

. .html()

recreates the tags so you lose all your events and stuff

+1


source







All Articles