Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move an element into another element?

I would like to move one DIV element inside another. For example, I want to move this (including all children):

<div id="source"> ... </div> 

into this:

<div id="destination"> ... </div> 

so that I have this:

<div id="destination">   <div id="source">     ...   </div> </div> 
like image 307
Mark Richman Avatar asked Aug 14 '09 20:08

Mark Richman


People also ask

How do you move an element from one element to another?

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.

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.


1 Answers

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>
like image 62
Andrew Hare Avatar answered Oct 06 '22 06:10

Andrew Hare