Skip to content
GitHub

Adding and Removing Elements

Switch to Zen Mode


The DOM API allows you to create new elements and insert them into the DOM tree.

Creates a new element with the specified tag name.

const newDiv = document.createElement("div");
newDiv.textContent = "Hey, I'm new!";
javascript

Creates a new text node with the given text content.

const textNode = document.createTextNode('Hello, World!');
javascript

Appends a new child node to an element.

const div = document.getElementById("container");
const newDiv = document.createElement("div");
const textNode = document.createTextNode('Hello, World!');
newDiv.appendChild(textNode);
div.appendChild(newDiv);
javascript

Inserts a new node before a reference node.

const parent = document.getElementById("container");
const newNode = document.createElement("p");
const reference = parent.children[1];
parent.insertBefore(newNode, reference);
javascript

Replaces an old child with a new one.

const parent = document.getElementById("container");
const newChild = document.createElement("span");
const oldChild = parent.firstChild;
parent.replaceChild(newChild, oldChild);
javascript

Creates a copy of an element. The deep parameter specifies whether to copy the element’s child nodes.

const clone = newDiv.cloneNode(true); // Deep clone
javascript

Inserts HTML content at a specified position relative to an element.

document.body.insertAdjacentHTML('beforeend', '<div>New Div</div>');
javascript

Removes a child element from the DOM.

const parent = document.getElementById("container");
const child = parent.firstChild;
parent.removeChild(child);
javascript
  • Removes the element itself from the DOM.
const div = document.getElementById("myDiv");
div.remove();
javascript