Home » Programming » Javascript » Javascript Appendchild

Use appendChild() in JavaScript to Add Page Elements [Examples]

The Node.appendChild() method adds a new HTML Element to the page (via the DOM). This article will show you how to use it.

The DOM in JavaScript

The HTML DOM (Document Object Model) is the interface which JavaScript uses to read from and interact with HTML page elements.

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

The DOM makes it super convenient to add, remove, and update both visible and invisible HTML elements on the page. For example, it is the ideal way to add rows to a table, or options to a drop down list from JavaScript based on user input or data being retrieved.

appendChild() Method Syntax

The appendChild() method must be called from a DOM Node object and has the following syntax:

NODE.appendChild(CHILD);

Note that:

  • 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.

The following JavaScript will add an item to the list using the appendChild() method:

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.

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment