How to move a div element into another element in HTML
Overview
In HTML, the appendChild method is used to move an element. This method will append the given node into the node in which the method is invoked.
Syntax
appendChild(childToAppend);
Syntax of appendChild method
Parameters
This method takes a parameter, childToAppend, which represents the node to be appended.
Return value
The method returns the appended node. In the case that the childToAppend is a document fragment, then an empty document fragment is returned.
Example
The below code demonstrates how to use the appendChild method to move a div element into another element.
Explanation
- Lines 5–7: We create a
divelement with the ID,element_to_move. - Lines 8–10: We create a
divelement with the ID,destination_parent. This element contains onep(paragraph) element as a child. We'll move thedivelement with the ID,element_to_move, into thisdivelement. - Line 12: We create a variable,
elementToMove, and assign thedivelement with the ID,element_to_move, as a value. - Line 13: We create a variable,
destinationElement, and assign thedivelement with the ID,destination_parent, as a value. - Line 16: We print the HTML content of
destinationElementusing theouterHTMLproperty. - Line 18: We invoke the
appendChildmethod ondestinationElementwithelementToMoveas an argument. This will move the element from thebodyand append it as the last child of thedestinationElement.