JavaScript appendchild(): What it is and when to use it
Tags: javascript, webdev, react, programming
Published: 2021-05-06 06:08:43

*This tutorial is a part of our initiative at [Flexiple](https://flexiple.com/), to write short curated tutorials around often used or interesting concepts.*

The JavaScript `appendChild()` method is used to insert a new node or reposition an existing node as the last child of a particular parent node.

**TABLE OF CONTENTS**

1. [Syntax of JavaScript appendChild](#syntax)
2. [What is the JavaScript appendChild() method?](#what)
3. [Key points to note: appendChild() method](#key)
4. [JavaScript appendChild(): Examples](#examples)
5. [JavaScript appendChild() vs. append()](#vs)
6. [Objects that support appendChild()](#objects)
7. [Browsers that support appendChild()](#browsers)

## Syntax of JavaScript appendChild:<a name="syntax"></a>

```
parentNode.appendChild(childNode);
```

The `childNode` is the node that we want to append to the parent node `parentNode`. `appendChild()` will return the appended child.

## What is the JavaScript appendChild() method?<a name="what"></a>

The JavaScript `appendChild()` is a method of the Node interface, used to append nodes (typically elements) at the end of a specified parent node. It can be executed on existing child nodes or by creating new elements:

### Creating elements

To create a new element to be inserted at the end of a parent node, first use createElement to create it and then `appendChild()` for the newly-created element.

### Existing elements

The `appendChild()` method also works on existing child nodes, using which you can move them to new positions within the document. In such a case, `appendChild()` moves the particular child node from its current position to a new position at the end of the list of child nodes under the specified parent node.

For appending existing child nodes to any other node, note that there is no need to remove the node from its parent node first. This is because a node can't be present in two positions within the same document simultaneously.

So, when you use `appendChild()` to append an existing child node to another node, the child node is first removed, and then appended at the new position.


## JavaScript appendChild(): Examples<a name="examples"></a>

### 1) Simple example

```javascript
// Create a new paragraph element, and append it to the end of the document body
let p = document.createElement("p");
document.body.appendChild(p);
```

### 2) How to use the appendChild() method

```javascript
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>How to use JavaScript appendChild()</title>
</head>
<body>
    <ul id="userprofile">
    </ul>
    
    <script>
        function createMenuItem(name) {
            let li = document.createElement('li');
            li.textContent = name;
            return li;
        }
        // get the ul#userprofile
        const userprofile = document.querySelector('#userprofile');
        // add the user profile items
        userprofile.appendChild(createMenuItem('Profile'));
        userprofile.appendChild(createMenuItem('Settings'));
        userprofile.appendChild(createMenuItem('Log out'));
    </script>
</body>
</html>
```

### 3) How to move an existing element within the same document using appendchild()

```javascript
<ul id="list1">
    <li>Chocolate</li>
    <li>Ice-cream</li>
    <li>Candy</li>
</ul>

<ul id="list2">
    <li>Chips</li>
    <li>Smoothie</li>
    <li>Soda</li>
</ul>

// get list1
const firstList = document.querySelector('#list1');
// get the first child element
const chocolate = firstList.firstElementChild;
// get list2
const secondList = document.querySelector('#list2');
// append chocolate to list2
secondList.appendChild(chocolate)
```

## Key points to note: appendChild() method<a name="key"></a>

* 'Appended' essentially means 'attach at the end'.
* You can use `cloneNode()` to make a clone of the node before appending it under a new parent. However, remember that the copies of nodes made using cloneNode won't be updated automatically.
* You cannot use the `appendChild()` method to append elements belonging to another document. For this, you'll first have to use `importNode` or `adoptNode` to import foreign elements, and then use `appendChild()` to insert them into the desired position.
* You can use the `removeChild` method to remove a child from an element.

## JavaScript appendChild() vs. append()<a name="vs"></a>

`append()` is a newer API that allows you to insert a set of DOMString objects (in addition to Node objects) as equivalent text nodes at the end of the list of child nodes of a parent node.

### Syntax of append()

```
parentNode.append()
```

### Difference between appendChild() and append()

#### 1. Node vs. DOMString objects

Unlike `parentNode.appendChild()`, which only allows you to append Node objects and return the appended Node object, `parentNode.append()` also allows you to append DOMString objects, and it has no return value.

#### 2. Single vs. Multiple arguments

Further, `parentNode.appendchild()` allows you to append only one node, while `parentNode.append()` supports multiple arguments - so you can append several nodes and strings.

## Objects that support appendChild()<a name="objects"></a>

The following JavaScript objects support the `appendChild()` method:

* attributedocument
* DocumentFragment
* XMLDocument

The following HTML elements support the `appendChild()` method:

```html
<a>, <b>, <big>, <blockquote>, <body>, <button>, <center>, <code>, <dir>, <div>, <dl>, <em>, <font>, <h1>, <h2>, <h3>, <h4>, <h5>, <h6>, <head>, <html>, <i>, <img>, <label>, <li>, <menu>, <object>, <ol>, <select>, <small>, <span>, <strike>, <strong>, <sub>, <sup>, <table>, <tfoot>, <th>, <thead>, <ul>, <var>, <xml>, <xmp>
```
And many others...

## Browsers that support appendChild()<a name="browsers"></a>

The following browsers support the appendChild() method:

* Google Chrome
* Mozilla Firefox
* Safari
* Microsoft Edge
* Opera

Read more about JavasCript appendchild on [Mozilla's official Web Docs](https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild).