move element to another element in js

How to Move Element into Another Element in jQuery

Often web developers need to move one element on their web pages into another element. You can easily do this using jQuery. In this article, we will learn how to move element into another element in jQuery. This is useful if you want to alter your page layout dynamically or without modifying its HTML code.


How to Move Element into Another Element in jQuery

Let us say you have two divs as shown below.

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

and

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

If you want to move div with id=’source’ to end of div with id=’destination’, use appendTo() function as shown below.

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

If you want to move div with id=’source’ to beginning of div with id=’destination’, use prependTo() function as shown below.

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

Please note, when you use appendTo() or prependTo() they both create copies of your source object. In case you don’t want this to happen and want to move original elements, use detach() function before calling appendTo() or prependTo().

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

If you prefer a pure JavaScript solution, or don’t use jQuery, then here is how to do this.

// 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);

In the above code, we first create a fragment element, then we append source element to this fragment and finally, we append the fragment to destination element.

In this article, we have learnt how to move element into another element using jQuery as well as JavaScript. You can use them to easily move DOM elements on your web page.

Also read:

How to Automatically Scroll to Bottom of Page in JS
How to Change Image Source in jQuery
How to Check for Hash in URL in JavaScript
How to Check if File Exists in NodeJS
How to Load Local JSON File

Leave a Reply

Your email address will not be published. Required fields are marked *