javascript-dom-manipulation
|

JavaScript DOM Manipulation: A Beginner’s Guide

Initially, JavaScript was built to manipulate the DOM and capture user interaction. Nowadays, JavaScript is far from that and has established itself as a powerful cross-platform language. Although the old-school method may not be as popular in the modern era of React, Vue, and other libraries, it still has a place. Learning DOM manipulation helps developers understand how frameworks manage and update the DOM efficiently (e.g., React’s virtual DOM).

It’s invaluable for debugging or enhancing legacy systems that rely heavily on direct DOM access.

What is DOM

The DOM, the Document Object Model, is a tree view of a page’s HTML structure. If we check a page’s source code, we see many nodes in parent-child relations. That’s the DOM.

What is DOM Manipulation

The DOM manipulation uses JavaScript to add, remove, and modify the HTML structure. We may need it to apply CSS, add attributes, remove/show/hide an element based on user interaction, and more.

DOM Manipulation

I will start by creating an element and manipulating it into a document.

Let’s assume we have a document with only a body tag, and we’ll add a few elements to it.

<body>

</body>
//creation of a div element and add class
const divElement = document.createElement("div");
divElement.classList.add("container");

//creation of a heading element add text
const heading = document.createElement("h1");
heading.textContent = "Hello ";

//creation of a span element and add class and text, set text color of the span
const span = document.createElement("span");
span.classList.add("highlight");
span.style.color = "red";
span.textContent = "World";

//creation of a heading2 element and add text
const heading2 = document.createElement("h2");
heading2.textContent = "Hello World 2";

//appending span element to the heading element
heading.appendChild(span);

//appending heading to the div element and span element to the heading element
divElement.append(heading, heading2);
            
//appending div element to the body
document.body.append(divElement);

To insert element, I used both the append and appendChild methods. There are subtle differences between them.

append is newer and more versatile, supporting text nodes and multiple elements, while appendChild is older and more limited. So, in place of textContent, we can use append to add text but not the appendChild method. An example will come later in this article.

Some selection methods

In the above code example, we selected the body tag using a pre-defined way of document. So, by writing document.body, we got access to the body tag. But what if we need to select a different element?

Here are 2 common ways to select elements.

  1. document.querySelector();
  2. document.querySelectorAll()

Both methods accept a string as a parameter. The querySelector() method will return the element as the node we want to select.

The querySelectorAll() method returns a Node List containing all the matched elements. A Node List is similar to an Array.

We can pass the selector to the above methods, like “.myElement,” “#myElement,” or “h1.” Class, ID, or element tags will work as selectors.

Something Complex

We’ll check the above 2 methods of selecting elements to see if they actually work and try some complex manipulation.

//select the span element
const spanElement = document.querySelector(".highlight");

//create a new span element and add text to it
const spanElement2 = document.createElement("span");
spanElement2.append("Colorful ");

//insert the new span element before the existing span element
heading.insertBefore(spanElement2, spanElement);

Here we used querySelector method to select the span element and class is our selector here. We can also use “span” as a selector or element ID (if any). These two methods also support nesting selection, like document.querySelector(".highlight .myCustomClass"). This will select the element with the class myCustomClass inside the .highlight element.

The insertBefore method is used to insert an element exactly before the referenced element. So, the code is now like below:

<body>
  <div class="container">
    <h1>
      Hello <span>Colorful </span>
      <span class="highlight" style="color: red">World</span>
    </h1>
    <h2>Hello World 2</h2>
  </div>
</body>

Note: If there is no referenced element, the new element will be inserted as the last child of the container/parent element.

More selection methods

There are a few more ways to select an element.

  1. document.getElementById()
  2. document.getElementsByTags()
  3. document.getElementsByClassName()

The getElementById() method can select a single element by ID. The other two methods will return a collection of nodes (if available) as NodeList.

While the querySelector and querySelectorAll methods are modern and more flexible, these three methods are faster for performance-sensitive tasks.

The innerHTML method

The innerHTML is commonly used to insert elements into DOM. This method treats everything as text even though you insert a node. Also, this method replace everything within the Node you’re inserting in.

The innerHTML can introduce security risks when working with user input (e.t., cross-site scripting);

Set attributes DOM manipulation

Now we know how to select an element and manipulate DOM. JavaScript provides setAttributes method to set a custom attribute to an element.

//select the highlighted span element by classname
const highlightedElement = document.getElementByClassName("highlight")[0];

//set a custom attribute
highlightedElement.setAttribute("data-site", "codespoetry.com");

In the above example, we selected an element by ClassName. Since this method returns a collection of nodes even if only one element exists, I used the index [0] to select the first element. We can use the index to select a specific element in case of multiple elements with the same class or tag.

One thing to note here, we can set any name as an attribute property. However, using data-[custom name] gives us the flexibility of accessing that attribute by highlightElement.dataset.site. So we don’t need to use the getAttribute method to access an attribute.

Similar to setAttribute, there is another method removeAttribute() to remove an attribute from an element.

I hope this article will help you learn and understand JavaScript DOM manipulation. Please share the article and leave feedback and suggestions in the comment box below.

Similar Posts

Leave a Reply