0
0
JavascriptHow-ToBeginner · 3 min read

How to Append Element in JavaScript: Simple Guide

To append an element in JavaScript, use parentElement.appendChild(newElement) to add a child node or parentElement.append(newElement) to add nodes or text. These methods add the new element as the last child inside the parent element.
📐

Syntax

The main ways to append elements in JavaScript are:

  • parentElement.appendChild(newElement): Adds a new child node to the end of the parent element's children.
  • parentElement.append(nodesOrStrings): Adds nodes or text to the end of the parent element. It can take multiple arguments.
javascript
parentElement.appendChild(newElement);

parentElement.append(newElement1, newElement2, "text");
💻

Example

This example creates a new div element and appends it to the body of the page. It shows how the new element appears as the last child.

javascript
const newDiv = document.createElement('div');
newDiv.textContent = 'Hello, I am new here!';
document.body.appendChild(newDiv);

// Using append to add multiple nodes and text
const span = document.createElement('span');
span.textContent = ' - appended span';
document.body.append(span, span, ' and some text');
Output
A new div with text 'Hello, I am new here!' appears at the end of the page body, followed by a span and text.
⚠️

Common Pitfalls

Common mistakes when appending elements include:

  • Trying to append a string with appendChild which only accepts nodes.
  • Appending the same element multiple times, which moves it instead of cloning.
  • Not creating the element first with document.createElement.
javascript
const parent = document.body;

// Wrong: appendChild with string (throws error)
// parent.appendChild('Hello');

// Right: use append for strings
parent.append('Hello');

// Wrong: appending same element twice
const el = document.createElement('p');
el.textContent = 'Text';
parent.appendChild(el);
parent.appendChild(el); // moves element, does not duplicate

// Right: clone if you want duplicates
const clone = el.cloneNode(true);
parent.appendChild(clone);
📊

Quick Reference

MethodDescriptionAcceptsNotes
appendChildAdds a single node as last childNode onlyThrows error if argument is not a node
appendAdds nodes or strings as last childrenNodes or stringsCan add multiple arguments, no error on strings
insertBeforeInserts a node before a reference nodeNode, NodeUseful for inserting at specific position

Key Takeaways

Use appendChild to add a single node as the last child of a parent element.
Use append to add multiple nodes or text strings at once to a parent element.
appendChild only accepts nodes; append accepts nodes and strings.
Appending the same element twice moves it instead of duplicating; clone if needed.
Always create elements with document.createElement before appending.