How To Make Changes to the DOM

Published on December 26, 2017
How To Make Changes to the DOM


In the previous two installments of the Understanding the DOM series, we learned How To Access Elements in the DOM and How To Traverse the DOM. Using this knowledge, a developer can use classes, tags, ids, and selectors to find any node in the DOM, and use parent, child, and sibling properties to find relative nodes.

The next step to becoming more fully proficient with the DOM is to learn how to add, change, replace, and remove nodes. A to-do list application is one practical example of a JavaScript program in which you would need to be able to create, modify, and remove elements in the DOM.

In this tutorial, we will go over how to create new nodes and insert them into the DOM, replace existing nodes, and remove nodes.

Creating New Nodes

In a static website, elements are added to the page by directly writing HTML in an .html file. In a dynamic web app, elements and text are often added with JavaScript. The createElement() and createTextNode() methods are used to create new nodes in the DOM.

Property/Method Description
createElement() Create a new element node
createTextNode() Create a new text node
node.textContent Get or set the text content of an element node
node.innerHTML Get or set the HTML content of an element

To begin, let’s create an index.html file and save it in a new project directory.

<!DOCTYPE html>
<html lang="en">

    <title>Learning the DOM</title>

    <h1>Document Object Model</h1>


Right click anywhere on the page and select “Inspect” to open up Developer Tools, then navigate to the Console.

We will use createElement() on the document object to create a new p element.

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

We’ve created a new p element, which we can test out in the Console.

  1. console.log(paragraph)

The paragraph variable outputs an empty p element, which is not very useful without any text. In order to add text to the element, we’ll set the textContent property.

  1. paragraph.textContent = "I'm a brand new paragraph.";
  2. console.log(paragraph)
<p>I'm a brand new paragraph.</p>

A combination of createElement() and textContent creates a complete element node.

An alternate method of setting the content of the element is with the innerHTML property, which allows you to add HTML as well as text to an element.

  1. paragraph.innerHTML = "I'm a paragraph with <strong>bold</strong> text.";

Note: While this will work and is a common method of adding content to an element, there is a possible cross-site scripting (XSS) risk associated with using the innerHTML method, as inline JavaScript can be added to an element. Therefore, it is recommended to use textContent instead, which will strip out HTML tags.

It is also possible to create a text node with the createTextNode() method.

  1. const text = document.createTextNode("I'm a new text node.");
  2. console.log(text)
"I'm a new text node."

With these methods, we’ve created new elements and text nodes, but they are not visible on the front end of a website until they’ve been inserted into the document.

Inserting Nodes into the DOM

In order to see the new text nodes and elements we create on the front end, we will need to insert them into the document. The methods appendChild() and 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.

Property/Method Description
node.appendChild() Add a node as the last child of a parent element
node.insertBefore() Insert a node into the parent element before a specified sibling node
node.replaceChild() Replace an existing node with a new node

To practice these methods, let’s create a to-do list in HTML:

  <li>Buy groceries</li>
  <li>Feed the cat</li>
  <li>Do laundry</li>

When you load your page in the browser, it will look like this:

DOM Screenshot 1

In order to add a new item to the end of the to-do list, we have to create the element and add text to it first, as we did in the “Creating New Nodes” section above.

  1. // To-do list ul element
  2. const todoList = document.querySelector('ul');
  3. // Create new to-do
  4. const newTodo = document.createElement('li');
  5. newTodo.textContent = 'Do homework';

Now that we have a complete element for our new to-do, we can add it to the end of the list with appendChild().

  1. // Add new todo to the end of the list
  2. todoList.appendChild(newTodo);

You can see the new li element has been appended to the end of the ul.

  <li>Buy groceries</li>
  <li>Feed the cat</li>
  <li>Do laundry</li>
  <li>Do homework</li>

DOM Screenshot 2

Maybe we have a higher priority task to do, and we want to add it to the beginning of the list. We’ll have to create another element, as createElement() only creates one element and cannot be reused.

  1. // Create new to-do
  2. const anotherTodo = document.createElement('li');
  3. anotherTodo.textContent = 'Pay bills';

We can add it to the beginning of the list using insertBefore(). This method takes two arguments — the first is the new child node to be added, and the second is the sibling node that will immediately follow the new node. In other words, you’re inserting the new node before the next sibling node. This will look similar to the following pseudocode:

parentNode.insertBefore(newNode, nextSibling);

For our to-do list example, we’ll add the new anotherTodo element before the first element child of the list, which is currently the Buy groceries list item.

  1. // Add new to-do to the beginning of the list
  2. todoList.insertBefore(anotherTodo, todoList.firstElementChild);
  <li>Pay bills</li>
  <li>Buy groceries</li>
  <li>Feed the cat</li>
  <li>Do laundry</li>
  <li>Do homework</li>

DOM Screenshot 3

The new node has successfully been added at the beginning of the list. Now we know how to add a node to a parent element. The next thing we may want to do is replace an existing node with a new node.

We’ll modify an existing to-do to demonstrate how to replace a node. The first step of creating a new element remains the same.

  1. const modifiedTodo = document.createElement('li');
  2. modifiedTodo.textContent = 'Feed the dog';

Like insertBefore(), replaceChild() takes two arguments — the new node, and the node to be replaced, as shown in the pseudocode below.

parentNode.replaceChild(newNode, oldNode);

We will replace the third element child of the list with the modified to-do.

  1. // Replace existing to-do with modified to-do
  2. todoList.replaceChild(modifiedTodo, todoList.children[2]);
  <li>Pay bills</li>
  <li>Buy groceries</li>
  <li>Feed the dog</li>
  <li>Do laundry</li>
  <li>Do homework</li>

DOM Screenshot 4

With a combination of appendChild(), insertBefore(), and replaceChild(), you can insert nodes and elements anywhere in the DOM.

Removing Nodes from the DOM

Now we know how to create elements, add them to the DOM, and modify existing elements. The final step is to learn to remove existing nodes from the DOM. Child nodes can be removed from a parent with removeChild(), and a node itself can be removed with remove().

Method Description
node.removeChild() Remove child node
node.remove() Remove node

Using the to-do example above, we’ll want to delete items after they’ve been completed. If you completed your homework, you can remove the Do homework item, which happens to be the last child of the list, with removeChild().

  1. todoList.removeChild(todoList.lastElementChild);
  <li>Pay bills</li>
  <li>Buy groceries</li>
  <li>Feed the dog</li>
  <li>Do laundry</li>

DOM Screenshot 5

Another method could be to remove the node itself, using the remove() method directly on the node.

  1. // Remove second element child from todoList
  2. todoList.children[1].remove();
  <li>Pay bills</li>
  <li>Feed the dog</li>
  <li>Do laundry</li>

DOM Screenshot 6

Between removeChild() and remove(), you can remove any node from the DOM. Another method you may see for removing child elements from the DOM is setting the innerHTML property of a parent element to an empty string (""). This is not the preferred method because it is less explicit, but you might see it in existing code.


In this tutorial, we learned how to use JavaScript to create new nodes and elements and insert them into the DOM, and replace and remove existing nodes and elements.

At this point in the Understanding the DOM series you know how to access any element in the DOM, walk through any node in the DOM, and modify the DOM itself. You can now feel confident in creating basic front-end web apps with JavaScript.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

Tutorial Series: Understanding the DOM — Document Object Model

The Document Object Model, usually referred to as the DOM, is an essential part of making websites interactive. It is an interface that allows a programming language to manipulate the content, structure, and style of a website. JavaScript is the client-side scripting language that connects to the DOM in an internet browser.

About the authors

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

very good documentation. I am very glad for finding this documentation.

Great tutorials! Your presentation and writing style is very clear!

I’ve been trying to learn more about innerHTML and thought XSS attacks were possible when using innerHTML connected to forms (i.e. user input). Otherwise, using innerHTML to just add HTML to the DOM isn’t vulnerable to XSS. Is that how you understand it, too?

function showAnswer() {
    const answer = "<p>The answer is <strong>Ada Lovelace</strong>!</p>";
    document.querySelector('body').innerHTML = answer;

I also looked into .insertAdjacentHTML() as a “safer” way to add HTML via JS.
An easy riff for appending is using the ‘beforeend’ 1st argument + the content to append.

function showAnswer() {
    const answer = "<p>The answer is <strong>Ada Lovelace</strong>!</p>";
    document.querySelector('body').insertAdjacentHTML('beforeend', answer);

These are really helpful. Thankyou!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Featured on Community

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel