The Node.appendChild() method adds a new HTML Element to the page (via the DOM). This article will show you how to use it.
It’s a data structure which represents every HTML tag present on the page – everything from the root <html> element that wraps your page to every <div>, <p>, <input>, and <em> – everything on the page is represented in the DOM, both content and structure.
Each HTML element is represented in the DOM as a Node – an abstraction of the on-page element.
Adding/Updating the DOM
appendChild() Method Syntax
The appendChild() method must be called from a DOM Node object and has the following syntax:
- NODE is the node you wish to append a child element to
- CHILD is the child element you wish to append to NODE
- The return value of appendChild() is the appended CHILD Node
- If the appended child is a parentless Document Fragment, and empty DocumentFragment is returned instead
Adding Elements using appendChild() – Examples
To use the appendChild() method, we must first have an HTML Element (which will be represented in the DOM) to work with. A list is a good example, as items can be added using appendChild():
<ul id="my-list"> <li>List item 1</li> <li>List item 2</li> </ul>
Above, a simple HTML list is created with the id of my-list.
var myList = document.getElementById('my-list'); var newListItem = document.createElement('li'); newListItem.innerText = 'List item 3'; myList.appendChild(newListItem);
First, the existing list in the HTML DOM is retrieved using getElementById().
Then, a new list item is created using createElement(). This is the new child element which will be appended.
The text for the new child element is set by setting it’s innerText property.
Finally, appendChild() can be used to append the new list item as a child object of the existing list my-list.
To remove a child element instead of adding it, use removeChild() instead.