JavaScript Node appendChild() method explained - with code examples

Posted on Mar 11, 2022

Learn how the JavaScript appendChild method works in the HTML DOM tree

The JavaScript appendChild() method is a method that’s available from the JavaScript Node object.

The method allows you to add a node as a child of the node where you call the method from. The given node will be added as the last child of the receiving node.

For example, you can append a <div> element to the <body> element using the following code:

let aDiv = document.createElement("div");

document.body.appendChild(div);

The end result is that the <div> will be added to the <body> tag:

<body>
  <div></div>
</body>

When the node already has a child node or more, the element will be added below the last child node.

For example, suppose you want to append a <span> element to the <body> tag above. Here’s the code you need to run:

let aSpan = document.createElement("span");
document.body.appendChild(span);

// Result:
<body>
  <div></div>
  <span></span>
</body>

The appendChild() method accepts only one argument: the Node object you want to append to the receiving node. This is usually an HTML element.

When you try to pass a string, JavaScript will throw a TypeError message like this:

Uncaught TypeError: Failed to execute 'appendChild' on 'Node':
parameter 1 is not of type 'Node'.

Finally, if you use an existing Node in the DOM tree as the argument to the appendChild() method, that element will be moved from its current position to the new position.

Suppose you have the following DOM tree in your HTML document:

<body>
  <div id="wrapper">
    <p id="paragraph">
      <span id="span"></span>
    </p>
  </div>
</body>

You can move the <span> element as a child of the <body> tag with the appendChild() method.

You just need to get the existing element first, then pass that element into the appendChild() method as shown below:

let span = document.getElementById("span");
document.body.appendChild(span);

// Result:
<body>
  <div id="wrapper">
    <p id="paragraph"></p>
  </div>
  <span id="span"></span>
</body>

Finally, the appendChild() method returns the argument you passed into it back.

You can use the returned value to do other operations, such as adding a text to it:

document.body.appendChild(span).innerText = "Hello!";

// The same as:
document.body.appendChild(span);
span.innerText = "Hello!";

// Result:
<body>
  <div id="wrapper">
    <p id="paragraph"></p>
  </div>
  <span id="span">Hello!</span>
</body>

You can call an Element or Node object method by chaining it to the returned value of the appendChild() method.

And that’s how the JavaScript appendChild() method works. 😉

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.