Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move Element to another div without losing events, listeners, etc (without jQuery)

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.

like image 263
Saahir Foux Avatar asked Oct 12 '14 03:10

Saahir Foux


People also ask

Are event listeners removed when element is removed?

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.

How do I move a div to another div?

Answer: Use the jQuery . appendTo() Method You can use the jQuery . appendTo() method to move an element into another element.

How do I move a DIV from one place to another in jQuery?

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.


1 Answers

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/

like image 126
cssyphus Avatar answered Oct 06 '22 00:10

cssyphus