JavaScript append() Method

Summary: in this tutorial, you’ll learn how to use the JavaScript append() method to insert a set of Node objects or DOMString objects after the last child of a parent node.

Introduction to JavaScript append() method

The parentNode.append() method inserts a set of Node objects or DOMString objects after the last child of a parent node:

parentNode.append(...nodes);
parentNode.append(...DOMStrings);Code language: JavaScript (javascript)

The append() method will insert DOMString objects as Text nodes.

Note that a DOMString is a UTF-16 string that maps directly to a string.

The append() method has no return value. It means that the append() method implicitly returns undefined.

JavaScript append() method examples

Let’s take some examples of using the append() method.

1) Using the append() method to append an element example

Suppose that you have the following ul element:

<ul id="app">
    <li>JavaScript</li>
</ul>Code language: HTML, XML (xml)

The following example shows how to create a list of li elements and append them to the ul element:

let app = document.querySelector('#app');

let langs = ['TypeScript','HTML','CSS'];

let nodes = langs.map(lang => {
    let li = document.createElement('li');
    li.textContent = lang;
    return li;
});

app.append(...nodes);Code language: JavaScript (javascript)

Output HTML:

<ul id="app">
    <li>JavaScript</li>
    <li>TypeScript</li>
    <li>HTML</li>
    <li>CSS</li>
</ul>Code language: HTML, XML (xml)

How it works:

  • First, select the ul element by its id by using the querySelector() method.
  • Second, declare an array of languages.
  • Third, for each language, create a new li element with the textContent is assigned to the language.
  • Finally, append li elements to the ul element by using the append() method.

2) Using the append() method to append text to an element example

Assume that you have the following HTML:

<div id="app"></div>Code language: HTML, XML (xml)

You can use the append() method to append a text to an element:

let app = document.querySelector('#app');
app.append('append() Text Demo');

console.log(app.textContent);Code language: JavaScript (javascript)

Output HTML:

<div id="app">append() Text Demo</div>Code language: HTML, XML (xml)

append vs. appendChild()

The following table shows the differences between append() and appendChild() methods:

Differencesappend()appendChild()
Return valueundefinedThe appended Node object
InputMultiple Node ObjectsA single Node object
Parameter TypesAccept Node and DOMStringOnly Node

Summary

  • Use the parentNode.append() method to append a set of Node objects or DOMString objects after the last child node of the parentNode.

Quiz

Was this tutorial helpful ?