JavaScript’s Element.append() method inserts a set of Node or string objects after the last child of the Element.
Syntax
Element.append(parameter1)
Element.append(parameter1, parameter2, /* … , */ parameterN)
Parameters
One or more Node or string objects.
Return value
The append() method does not have a return value, which means that the method implicitly returns undefined.
Exceptions
HierarchyRequestError DOMException
Thrown when the node cannot be inserted at the specified point in the hierarchy.
Examples
Here are some examples of using the JavaScript append() method.
Appending an element
Suppose we have the following unordered list to which we would like to add more languages:
<ul id="list">
<li>JavaScript</li>
</ul>
What should we do?
Well, we should create more li elements and append them to the ul element:
let list = document.getElementById('list');
let languages = ['C#', 'Java', 'Python'];
let nodes = languages.map(language => {
let li = document.createElement('li');
li.textContent = language;
return li;
});
list.append(...nodes);
Now our HTML looks like this:
<ul id="list">
<li>JavaScript</li>
<li>C#</li>
<li>Java</li>
<li>Python</li>
</ul>
Here is how our HTML looks like in the browser:
- JavaScript
- C#
- Java
- Python
So, what did we do?
First we used the getElementById() method to select the ul element by its id. Then we declared an array of programming languages. For each language, we created a new li element and set the element’s textContent. Finally, we used the spread operator (...) to expand the array of li elements and appended the elements to the ul element.
Appending text
Now we would like to append some text to the first li element in our list of programming languages. We can do that by selecting the li element with the querySelector() method and using the append() method:
let first = document.querySelector('#list li:first-child');
first.append(' is number one');
Here is our HTML after the changes:
<ul id="list">
<li>JavaScript is number one</li>
<li>C#</li>
<li>Java</li>
<li>Python</li>
</ul>
What is the difference between append() and appendChild()?
The append() and appendChild() methods have some noteworthy differences:
- With
Element.append(), you can append severalNodeand string objects; withNode.appendChild(), you can only append oneNodeobject. append()does not have a return value;Node.appendChild()returns the appendedNodeobject.
Browser compatibility
|
Chrome
|
Edge
|
Firefox
|
Internet Explorer
|
Opera
|
Safari
|
Chrome (Android)
|
Firefox (Android)
|
Opera (Android)
|
Safari (iOS)
|
Samsung Internet
|
WebView (Android)
|
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
append() |
54 | 17 | 49 | 41 | 10 | 54 | 49 | 41 | 10 | 6.0 | 54 | |