javascript - How to move an element into another element?

ID : 541

viewed : 235

Tags : javascriptjqueryhtmljavascript





Top 5 Answer for javascript - How to move an element into another element?

vote vote

100

You may want to use the appendTo function (which adds to the end of the element):

$("#source").appendTo("#destination"); 

Alternatively you could use the prependTo function (which adds to the beginning of the element):

$("#source").prependTo("#destination"); 

Example:

$("#appendTo").click(function() {    $("#moveMeIntoMain").appendTo($("#main"));  });  $("#prependTo").click(function() {    $("#moveMeIntoMain").prependTo($("#main"));  });
#main {    border: 2px solid blue;    min-height: 100px;  }    .moveMeIntoMain {    border: 1px solid red;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <div id="main">main</div>  <div id="moveMeIntoMain" class="moveMeIntoMain">move me to main</div>    <button id="appendTo">appendTo main</button>  <button id="prependTo">prependTo main</button>

vote vote

83

my solution:

MOVE:

jQuery("#NodesToMove").detach().appendTo('#DestinationContainerNode') 

COPY:

jQuery("#NodesToMove").appendTo('#DestinationContainerNode') 

Note the usage of .detach(). When copying, be careful that you are not duplicating IDs.

vote vote

79

What about a JavaScript solution?

// Declare a fragment: var fragment = document.createDocumentFragment();  // Append desired element to the fragment: fragment.appendChild(document.getElementById('source'));  // Append fragment to desired element: document.getElementById('destination').appendChild(fragment); 

Check it out.

vote vote

67

I just used:

$('#source').prependTo('#destination'); 

Which I grabbed from here.

vote vote

51

Ever tried plain JavaScript... destination.appendChild(source); ?

onclick = function(){ destination.appendChild(source); }
div{ margin: .1em; }   #destination{ border: solid 1px red; }  #source {border: solid 1px gray; }
<!DOCTYPE html>  <html>     <body>      <div id="destination">     ###    </div>    <div id="source">     ***    </div>     </body>  </html>

Top 3 video Explaining javascript - How to move an element into another element?







Related QUESTION?