JavaScript append
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 itsid
by using thequerySelector()
method. - Second, declare an array of languages.
- Third, for each language, create a new
li
element with thetextContent
is assigned to the language. - Finally, append
li
elements to theul
element by using theappend()
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()
Here are the differences between append()
and appendChild()
:
Differences | append() | appendChild() |
Return value | undefined | The appended Node object |
Input | Multiple Node Objects | A single Node object |
Parameter Types | Accept Node and DOMString | Only Node |
Summary
- Use the
parentNode.append()
method to append a set ofNode
objects orDOMString
objects after the last child node of theparentNode
.