How to manipulate the DOM

In this article, we are going to learn how to manipulate the DOM:

  • Create an element
  • Set text content/ innerHTML of an element
  • Append an element
  • Insert one element before another
  • Replace a child element
  • Remove a child element
  • Change inline style

I. How to create an element

document.createElement(tagName) creates a new element of tagName.

For example: We want to add another li tag with JavaScript.

const li = document.createElement('li');

This function does NOT put a new element into the DOM. It creates it in memory so we can manipulate the element (such as adding text, styles, classes, ids, etc.) before placing it on the page.

II. How to add text content

To add text content, we use .textContent or innerTextto create a text node.

For example, we have these items on the list

<ul class="items">
    <li class="item">Item 1</li>
    <li class="item">Item 2</li>
    <li class="item">Item 3</li>
</ul>

In this example, we change the text content of the first element to “Good afternoon” and the content of the 2nd element to “Good afternoon”.

const ul = document.querySelector('.items');
ul.firstElementChild.textContent = "Good afternoon";
ul.children[1].innerText = "Good afternoon";

The difference between innerText and textContent is that textContent returns the content of all elements, including <script> and <style> elements. In contrast, innerText only shows the visible text contained in a node.

III. How to add HTML content

To add HTML content, we use .innerHTML.

const ul = document.querySelector('.items');
ul.lastElementChild.innerHTML = "<h2>Good evening</h2>";

It’s recommended to use textContent for adding text because innerHTML can create security risks if misused.

IV. How to append an item

For example, we create an element and inserting its text node. However, this element is not part of the DOM tree yet.

To append it to HTML page, we use appendChild() method.

parentNode.appendChild(childNode)

Example:

const li = document.createElement('li');
const innerhtml = li.textContent = "Hello";
const ul = document.querySelector('.items');
ul.appendChild(li);
console.log(ul);

We will get this result

<ul class="items">
    <li class="item">Item 1</li>
    <li class="item">Item 2</li>
    <li class="item">Item 3</li>
    <li>Hello</li>
</ul>

V. How to insert one element before another

To insert a new element before another element, we use insertBefore() method:

parentNode.insertBefore(newNode, existingNode)

Example: We insert a new item before the last item in the list.

const ul = document.querySelector(".items");

const li = document.createElement("li");
const innerhtml = (li.textContent = "Hello");

ul.insertBefore(li, ul.lastElementChild);
console.log(ul);

We will get this result

<ul class="items">
    <li class="item">Item 1</li>
    <li class="item">Item 2</li>
    <li>Hello</li>
    <li class="item">Item 3</li>
</ul>

VI. How to replace a child element

To replace a child element, we use replaceChild() method.

parentNode.replaceChild(newNode, existingNode)

Example: We replace the 2nd item to a new item.

const ul = document.querySelector(".items");

const li = document.createElement("li");
const innerhtml = (li.textContent = "Hello");

ul.replaceChild(li, ul.children[1]);
console.log(ul);

We will get this result

<ul class="items">
    <li class="item">Item 1</li>
    <li>Hello</li>
    <li class="item">Item 3</li>
</ul>

VII. How to remove a child element

We select the ul node.

const ul = document.querySelector('.items');

We can remove all items with remove() method:

ul.remove(); // All items are gone

or we can remove the first or last item

ul.firstElementChild.remove(); // Item 1 is gone
ul.lastElementChild.remove(); // Item 3 is gone

VIII. Add style

We can add inline style to DOM elements with .style.

Example:

const divStyle = document.querySelector("div").style;

divStyle.backgroundColor = "blue";
divStyle.border = "2px solid black";
divStyle.width = "80px";
divStyle.height = "50px";

Tips: Check DOM Enlightenment for more style rules.

IX. Working with classes

We can modify class values in an element.

MethodDescriptionExample
classNameSet class namediv.className;
classList.add()Add one or more class namesdiv.classList.add(‘btn’);
classList.toggle()Toggle a class on or offdiv.classList.toggle(‘btn’);
classList.contains()Check if class name existsdiv.classList.contains(‘btn’);
classList.replace()Replace an existing class name with a new onediv.classList.replace(‘old’, ‘new’);
classList.remove()Remove a class namediv.classList.remove(‘btn’);