JavaScript appendChild() Method Tutorial

In this section, we will learn what the appendChild() method is and how to use it in JavaScript.

What is Element appendChild() Method in JavaScript?

The JavaScript Element appendChild() method is used to append a new element as the direct child of an element.

Basically, using this method, we can add a new element as the direct child of an element which will appear as its last item.

Note: as mentioned before, using this method will put the new element as the last element. Now if we want to set an element as the child of another element but not necessarily as its last child, we can use the insertBefore() method.

Element appendChild() Method Syntax:

element.appendChild(element);

Element appendChild() Method Parameter

The method takes one argument and that is a reference to the element we want to add as the last child (direct child) of an element.

Element appendChild() Method Return Value

The method returns a reference to the node element that we’ve just set as the argument of the method.

Example: appendChild() in JavaScript

See the Pen appendChild() in JavaScript by Omid Dehghan (@odchan1) on CodePen.

Example: document body appendChild

See the Pen document body appendChild by Omid Dehghan (@odchan1) on CodePen.

Example: append element JavaScript

See the Pen append element JavaScript by Omid Dehghan (@odchan1) on CodePen.

Note that here we’ve appended a text-node to the <p> element and then appended this element to the <body> of the document.

Example: JavaScript add element to div

See the Pen JavaScript add element to div by Omid Dehghan (@odchan1) on CodePen.

Leave a Reply