JS: appendChild (Append Element as Child)

By Xah Lee. Date: . Last updated: .

node.appendChild(newNode)

Append newNode as child to node, but also remove newNode from its original parent (if it has one), if both are in the same document.

Return the appended newNode.

// get first paragraph
const fp = document.getElementsByTagName("p")[0];

// move it to bottom of body
document.body.appendChild(fp);

You can copy the above code and test it in browser console.

Copy and Append Node

To stop it from moving, you can make a clone first.

// get first paragraph
const fp = document.getElementsByTagName("p")[0];

// clone and add it to bottom of body
document.body. appendChild(fp.cloneNode(true));

Note: cloneNode makes a copy.

back to JS: DOM Methods

BUY ΣJS JavaScript in Depth