Simply put, I'm trying to move a submenu from one location to another. (Easy) I need to do this without losing any event handlers, etc. (Harder)
<ul id="Menu A">
<li id="submenu">My Submenu with Clicky Events</li>
</ul>
<ul id="Menu B">
<!--This is where I want to move #submenu (with) all its' events intact -->
</ul>
I've tried the following without success:
var submenu = $('#submenu').clone(true,true);
submenu.prependTo('.Menu B');
Ideally, I can find a solution without using jQuery, but if you have a solution that works with it, that would be okay.
In modern browsers, if a DOM Element is removed, its listeners are also removed from memory in javascript. Note that this will happen ONLY if the element is reference-free. Or in other words, it doesn't have any reference and can be garbage collected. Only then its event listeners will be removed from memory.
Answer: Use the jQuery . appendTo() Method You can use the jQuery . appendTo() method to move an element into another element.
All you have to do is select the element(s) you want to move, then call an “adding” method such as append() , appendTo() or prepend() to add the selected elements to another parent element. jQuery automatically realises that the element(s) to add already exist in the page, and it moves the element(s) to the new parent.
With jQuery you can use .appendTo()
$('#element_to_move').appendTo('#PARENT_at_destination');
jQuery will cut it from its present location and move it to the new location, without losing bindings etc. However, styles could be affected because the DOM location will change.
This could also be helpful: https://api.jquery.com/detach/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With