DEV Community

Cover image for JavaScript appendchild(): What it is and when to use it
hrishikesh1990
hrishikesh1990

Posted on • Updated on • Originally published at flexiple.com

JavaScript appendchild(): What it is and when to use it

This tutorial is a part of our initiative at Flexiple, 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
  2. What is the JavaScript appendChild() method?
  3. Key points to note: appendChild() method
  4. JavaScript appendChild(): Examples
  5. JavaScript appendChild() vs. append()
  6. Objects that support appendChild()
  7. Browsers that support appendChild()

Syntax of JavaScript appendChild:

parentNode.appendChild(childNode);
Enter fullscreen mode Exit fullscreen mode

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?

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

1) Simple example

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

2) How to use the appendChild() method

<!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>
Enter fullscreen mode Exit fullscreen mode

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

<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)
Enter fullscreen mode Exit fullscreen mode

Key points to note: appendChild() method

  • '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()

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()
Enter fullscreen mode Exit fullscreen mode

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()

The following JavaScript objects support the appendChild() method:

  • attributedocument
  • DocumentFragment
  • XMLDocument

The following HTML elements support the appendChild() method:

<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>
Enter fullscreen mode Exit fullscreen mode

And many others...

Browsers that support appendChild()

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.

Top comments (2)

Collapse
 
wdpdfpjrwkrszhs profile image
56835

Tip - you can use e.g. "html" or "javascript" to get syntax coloring on code blocks - just put it straight after the opening backticks. Cheers!

Collapse
 
hrishikesh1990 profile image
hrishikesh1990

Thanks! Neat trick, just added it