Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
html
div

How to move a div element into another element in HTML

Programming Bytes

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.

Console
Using append child method to move div element to another element

Explanation

  • Lines 5–7: We create a div element with the ID, element_to_move.
  • Lines 8–10: We create a div element with the ID, destination_parent. This element contains one p (paragraph) element as a child. We'll move the div element with the ID, element_to_move, into this div element.
  • Line 12: We create a variable, elementToMove, and assign the div element with the ID, element_to_move, as a value.
  • Line 13: We create a variable, destinationElement, and assign the div element with the ID, destination_parent, as a value.
  • Line 16: We print the HTML content of destinationElement using the outerHTML property.
  • Line 18: We invoke the appendChild method on destinationElement with elementToMove as an argument. This will move the element from the body and append it as the last child of the destinationElement.

RELATED TAGS

communitycreator
html
div
RELATED COURSES

View all Courses

Keep Exploring