HTML DOM Element appendChild() method

Definition and usage

appendChild() The method adds a node (element) as the last child element to the element.

See also:

insertBefore() method

replaceChild() method

removeChild() method

remove() method

childNodes property

firstChild property

lastChild property

firstElementChild property

lastElementChild property

Related document methods:

createElement() method

createTextNode() method

Instance

Example 1

Add items to a list:

const node = document.createElement("li");
const textnode = document.createTextNode("Water");
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);

Before adding:

  • Coffee
  • Tea

After adding:

  • Coffee
  • Tea
  • Water

Try It Yourself

Example 2

Move list items from one list to another:

const node = document.getElementById("myList2").lastElementChild;
document.getElementById("myList1").appendChild(node);

Before moving:

  • Coffee
  • Tea

  • Water
  • Milk

After moving:

  • Coffee
  • Tea
  • Milk

  • Water

Try It Yourself

Example 3

Create a paragraph with text:

  • Create a paragraph element
  • Create a text node
  • Append a text node to the paragraph
  • Append a paragraph to the document

Create a <p> element and append it to the <div> element:

const para = document.createElement("p");
const node = document.createTextNode("This is a paragraph.");
para.appendChild(node);
document.getElementById("myDIV").appendChild(para);

Try It Yourself

Example 4

Create a <p> element and append it to the body of the document:

const para = document.createElement("P");
const node = document.createTextNode("This is a paragraph.");
para.appendChild(node);
document.body.appendChild(para);

Try It Yourself

Syntax

element.appendChild(node)

or

node.appendChild(node)

Parameter

Parameter Description
node Required. The node to be appended.

Return Value

Type Description
Node The appended node.

Browser Support

element.appendChild() It is a DOM Level 1 (1998) feature.

All browsers fully support it:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support 9-11 Support Support Support Support