In this article, weā€™re going to learn all about how we can add, change, replace, and remove nodes from the DOM. Weā€™ll be looking specifically at theĀ createElement()Ā andĀ createTextNode()Ā methods.

Creating New Nodes

Let's create the following HTML file:

<html lang="en">
<head>
    <title>Master the DOM!</title>
  </head>
<body>
    <h1>Master the DOM!</h1>
  </body>
</html>

Open up theĀ ConsoleĀ tab in Developer Tools.

Letā€™s use theĀ createElement()Ā method on theĀ documentĀ object to create a newĀ pĀ element.

const paragraph = document.createElement('p');

console.log(paragraph);     // <p></p>

Success! TheĀ paragraphĀ variable gives us ourĀ pĀ element.

We can now add text to our element, with theĀ textContentĀ property:

paragraph.textContent = "I'm a paragraph!";

console.log(paragraph);     // <p>I'm a paragraph!</p>

By combiningĀ createElement()Ā andĀ textContentĀ we can create a complete element node.

We could also use theĀ innerHTMLĀ property to add content to an element.Ā With this property we can add both text and HTML to our element:

paragraph.innerHTML = "I'm a <strong>bold</strong> paragraph!";

Of the two methods,Ā textContentĀ is superior ā€” itā€™s slightly faster to render thanĀ innerHTML.

Itā€™s also possible to create a text node using theĀ createTextNode()Ā method:

const text = document.createTextNode("I'm a text node!");

console.log(text);    // "I'm a text node!"

All of these methods have created new elements and text nodes, however,Ā they are not visible on the front end of a website until theyā€™ve been inserted into the document!

Inserting Nodes into the DOM

To see the new text nodes and elements we create on the front end, we need to insert them into theĀ document.Ā The methodsĀ appendChild()Ā &Ā insertBefore()Ā are used to add items to the beginning, middle, or end of a parent element, andĀ replaceChild()Ā is used to replace an old node with a new node.

Let's demo this by adding a list to our HTML:

<ul>
  <li>Get pizza</li>
  <li>Get burgers</li>
  <li>Get Doritos</li>
</ul>

And hereā€™s our page:

DOM Example

Say we want to add a new item to the end of our list, we have to create the element and add text to it first, as we did previously, like so:

// Get the ul element
const list = document.querySelector('ul');

// Create new list item
const newItem = document.createElement('li');
newItem.textContent = 'Get nice cheese';

We now have a complete element for our new list item! So we can add it to the end of the list usingĀ appendChild():

// Add our new item to the end of the list
list.appendChild(newItem);

And our newĀ liĀ element has been appended to the end of theĀ ul:

DOM Example

To add an item to the beginning of our list, letā€™s create another element (we have to again create a new element,Ā asĀ createElement()Ā canā€˜t be reused):

// Create a new list item
const anotherNewItem = document.createElement('li');
anotherNewItem.textContent = 'Get Party Whistles';

We use theĀ insertBefore()Ā method to add it to the beginning of our list. It will take two arguments, the first being the new child node to be added, and the second is the sibling node that will immediately follow.

parentNode.insertBefore(newNode, nextSibling);

So for our example, weā€™ll add the newĀ anotherNewItemĀ element to the start of our list, like so:

// Add a new item to the beginning of the list
list.insertBefore(anotherNewItem, list.firstElementChild);

DOM Example

And now our new node has been added to the start of our list!

Letā€™s also take a look at how we can replace an existing node with a new node usingĀ replaceChild(). First, we create a new element:

const modifiedItem = document.createElement('li');
modifiedItem.textContent = "Get Poppin' Jalapeno Doritos";

replaceChild()Ā also takes two arguments, first the new node, then the node to be replaced...

parentNode.replaceChild(newNode, oldNode);

In our example, weā€™re replacing the third element child on our list:

// Replace list item
list.replaceChild(modifiedItem, list.children[3])

DOM Example

Using a combination ofĀ appendChild(),Ā insertBefore(), andĀ replaceChild(), we can insert nodes and elements anywhere in the DOM!

Removing Nodes from the DOM

To remove nodes from the DOM, we can useĀ removeChild()Ā to remove child nodes from their parent, or we can useĀ remove()Ā to remove the node itself.

Returning to our example let's remove the last item on our list:

// Remove the last list item
list.removeChild(list.lastElementChild);

And the result:

DOM Example

Alternatively, we could useĀ remove(), to remove the node itself:

// Remove the third element from our list
list.children[2].remove();

DOM Example

UsingĀ removeChild()Ā andĀ remove(), you can remove any node from the DOM.

In the next tutorial, weā€™ll take a look at how we can modify classes & styles in the DOM. By modifying HTML element nodes.

Related Posts:


Tim profile image

A little about me..

Hey, Iā€™m Tim! šŸ‘‹

Iā€™m a freelance business owner, web developer & author. I teach both new and experienced freelancers how to build a sustainable and successful freelancing business. Check out myĀ Complete Guide to Freelancing if you'd like to find out more.

While you're here, you can browse through my blogs where I post freelancing tips, code tutorials, design inspiration, useful tools & resources, and much more! You can also join the newsletter, or find me on X.

Thanks for reading! šŸŽ‰