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.
If you want to move div with id=’source’ to end of div with id=’destination’, use appendTo() function as shown below.
If you want to move div with id=’source’ to beginning of div with id=’destination’, use prependTo() function as shown below.
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().
// 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.
How to Automatically Scroll to Bottom of Page in JS
How to Change Image Source in jQuery
How to Check if File Exists in NodeJS
How to Load Local JSON File