DEV Community

Cover image for Understanding DOM Manipulation with JavaScript
Scofield Idehen
Scofield Idehen

Posted on • Originally published at blog.learnhub.africa

Understanding DOM Manipulation with JavaScript

Document Object Model or DOM is a programming interface that allows JavaScript to manipulate elements in an HTML document.

When an HTML code is loaded in a browser, it parses it. In order to make these web pages and HTML documents dynamic, the browser lets JavaScript tap into the power of the DOM to access nodes and elements within the HTML file in a hierarchical form.

DOM is an Application Programming Interface (API) for accessing and manipulating HTML files.

In this article, we will look at how to use the document object to select elements, traverse the DOM, insert, remove, and replace elements.

Selecting Elements in the DOM

You can select elements within the Document Object Model (DOM) using various methods available through the document object. These methods allow you to select either a single element or multiple elements. These methods are:

getElementById()

document.getElementById() access elements with a specific id that matches the one mentioned in the string.

<html>
          <head>
                <title>DOM Manipulation</title>
               <script src="./app.js" defer></script>
          </head>
          <body>
                <h1 id="heading"> JavaScript getElementById() 
              </h1>
            <ul class="parent">
                   <li class="item">First Item</li>
                   <li class="item">Second Item</li>
              </ul>
          </body>
</html>
Enter fullscreen mode Exit fullscreen mode
const element = document.getElementById("heading");
Enter fullscreen mode Exit fullscreen mode

The id is unique within an HTML document. However, HTML is a forgiving language. If the HTML document has multiple elements with the same id, the document.getElementById() method returns the first element it encounters. In cases where the ID given does not exist, it returns null.

getElementByClassName()

document.getElementByClassName() is used to access elements with specific class names. These names would be passed as arguments to the method when it is called.

It returns an array-like (not everything you can do on an array works there) object of the child elements with a specified class name.

These arrays are called HTML collections and are different from true Javascript arrays. Therefore, not all array operations can work with these HTML collections.

Just like document.getElementById(), document.getElementByClassName() method returns the first element it encounters. In cases where the class name given does not exist, it returns null.

Here is a code snippet that describes how getElementsByClassName() works with HTML elements:

<html>
          <head>
               <title>DOM Manipulation</title>
                <script src="./app.js" defer></script>
          </head>
          <body>
                <nav>
                <ul class="parent">
                    <li class="item">First Item</li>
                    <li class="item">Second Item</li>
                 </ul>
                </nav>
          </body>
</html>
Enter fullscreen mode Exit fullscreen mode
const items = document.getElementsByClassName("item");
Enter fullscreen mode Exit fullscreen mode

In the code snippet, the first element with the class item is selected and stored in a variable items.

querySelector()

document.querySelector() is a method that allows you to select the first element that matches the CSS selector.

<html>
          <head>
                <title>DOM Manipulation</title>
                <script src="./app.js" defer></script>
          </head>
          <body>
               <nav>
               <ul>
                    <li class="item">First Item</li>
                  <li class="item">Second Item</li>
                  <li class="item">Third Item</li>
               </ul>
               </nav>
          </body>
</html>
Enter fullscreen mode Exit fullscreen mode
const items = document.querySelector("li");
console.log(items);
Enter fullscreen mode Exit fullscreen mode

In this code, the js script uses the document.querySelector("li") to select the first li element.

Selecting Multiple Elements in the DOM

When it comes to selecting multiple elements within the DOM, there are several methods you can use. These methods typically return a collection of elements that matches specific criteria. Here are some commonly used approaches:

querySelectorAll()

document.querySelectorAll() is used to select all elements with a CSS selector. It returns a static NodeList of elements. This means it does not change or reflect when tag names are deleted or added.

<html>
          <head>
                <title>DOM Manipulation</title>
                <script src="./app.js" defer></script>
          </head>
          <body>
               <nav>
               <ul>
                    <li class="item">First Item</li>
                  <li class="item">Second Item</li>
                  <li class="item">Third Item</li>
               </ul>
               </nav>
          </body>
</html>
Enter fullscreen mode Exit fullscreen mode
const items = document.querySelectorAll("li");
console.log(items);
Enter fullscreen mode Exit fullscreen mode

From the above JavaScript code, we can easily select all the elements with the li CSS selector.

P S: This should not be confused with querySelector(). querySelector() selects just the first element with a specific CSS selector. While querySelectorAll() selects all elements with a specific CSS selector

getElementByTagName()

document.getElementByTagName() allows the selection of all elements that match a tag name. It returns a live HTMLCollection of elements. This means it automatically reflects changes when tag names are deleted or added. For example,

<html>
          <head>
                <title>DOM Manipulation</title>
                <script src="./app.js" defer></script>
          </head>
          <body>
                <h1>Tag Name 1</h1>
                <p>This is for some random text</p>
               <h1>Tag Name 2</h1>
                <p>This is for some more random text</p>
                <h1>Tag Name 3</h1>
                <p>This is for some other random text</p>
          </body>
</html>
Enter fullscreen mode Exit fullscreen mode
const headings = document.getElementsByTagName("h1");
console.log(headings);
Enter fullscreen mode Exit fullscreen mode

In the JavaScript code snippet, all of the elements with the tag name h1 are selected and displayed.

Traversing the DOM

DOM Traversing is the process of moving or selecting an element from another element.

It involves navigating the Document Object Model(DOM) tree to access and manipulate elements.

Traversing can occur in three directions:

  • Upwards
  • Sideways
  • Downwards

Upward traversing

This involves accessing a child element from its parent element or ancestors. The most common method used for upward traversing is parentElement().

Using parentElemet or parentNode

You can traverse up the DOM using parentElement() or parentNode(). This lets you access the element/node that encloses the current element.

<html>
          <head>
                <title>DOM Manipulation</title>
                <script src="./app.js" defer></script>
          </head>
         <body>
            <ul class="parent">
                <li class="child">First Item</li>
               <li class="child">Second Item</li>
                <li class="child">Third Item</li>
             </ul>
         </body>
</html>
Enter fullscreen mode Exit fullscreen mode
const item = document.querySelector(".child");
const parentN = item.parentNode
const parentEl = item.parentElement
console.log(parentN);
console.log(parentEl)
Enter fullscreen mode Exit fullscreen mode

In the JavaScript code snippet, the first element with the class child is selected and stored in a variable item. Now, we can use the parentNode and parentElement methods to access this element's parent node and parent element.

Sideways traversing

This involves moving between elements that share the same parent. These elements are also referred to as sibling elements. The most common methods used for sideways traversing are nextElementSibling and previousElementSibling

Using nextElementSibling and previousElementSibling

When navigating the DOM sideways we can select the next element using nextElementSibling and select the previous element using previousElementSibling.

<html>
          <head>
                <title>DOM Manipulation</title>
                <script src="./app.js" defer></script>
          </head>
          <body>
            <ul class="parent">
                <li class="child">First Item</li>
               <li class="child">Second Item</li>
                <li class="child">Third Item</li>
             </ul>
         </body>
</html>
Enter fullscreen mode Exit fullscreen mode
const firstItem = document.querySelector("li");
console.log(firstItem.nextElementSibling);
const secondItem = document.querySelectorAll("li")[1];
console.log(secondItem.previousElementSibling);
Enter fullscreen mode Exit fullscreen mode

This might be a bit confusing so let’s break down the code:

Line 1 we select the first element with the tag name li and store it in a variable named firstItem.

Line 2 we easily access the next element of the firstItem using the nextElementSibling method.

In line 3 we use querySelectorAll() to access all elements with the tag li, then we use the index [1] to select just the second element with the tag li, storing it in a variable named secondItem

Line 4 we easily access the previous element of secondItem using the previousElementSibling() method.

PS: This should give further clarity on the differences between querySelector() and querySelectorAll() and how they are used.

Downward Traversing

This involves moving from a parent element to its child elements. In navigating the DOM downwards, we can use the children property to select direct descendants of the current element.

Selecting children Element

In navigating the DOM downwards, we can use the children property to select direct descendants of the current element.

<html>
          <head>
                <title>DOM Manipulation</title>
                <script src="./app.js" defer></script>
          </head>
          <body>
            <ul class="parent">
                <li class="child">First Item</li>
               <li class="child">Second Item</li>
                <li class="child">Third Item</li>
             </ul>
         </body>
</html>
Enter fullscreen mode Exit fullscreen mode
<pre><code class="language-javascript">const parent = document.querySelector(".parent");
const children = parent.children;
Enter fullscreen mode Exit fullscreen mode

In the JavaScript code snippet, the first element with the class parent is selected and stored in a variable parent. Now, we can use the children method to access the element's descendants.

Creating HTML Elements in JavaScript

We can create new HTML elements from a Javascript code using the document.createElement() method. This method takes an argument of the type of element we want to create.

For example:

<html>
          <head>
                <title>DOM Manipulation</title>
                <script src="./app.js" defer></script>
          </head>
          <body>
            <ul class="parent">
                <li class="child">First Item</li>
               <li class="child">Second Item</li>
                <li class="child">Third Item</li>
             </ul>
         </body>
</html>
Enter fullscreen mode Exit fullscreen mode

We can use the createElement() method to create a new <li> element in JavaScript code.

const newList = document.createElement("li");

Now, we can easily add some content to the newList using the textContent method;

const newList = document.createElement("li");
newList.textContent = "Fourth Item";
console.log(newList)
Enter fullscreen mode Exit fullscreen mode

The output would be "Fourth Item".

Quite interesting, isn't it? With this, we can easily add elements and text content into existing HTML code in just a few lines. We can now go ahead to insert this into the existing list in the HTML code as a fourth Item.

Inserting Elements

We have seen how we can select and create elements, now we can easily insert elements in the DOM.

We can easily do this using the append() or appendChild() method. For example, we would use one of these to insert a new list as the Fourth Item in the HTML code.

<html>
          <head>
                <title>DOM Manipulation</title>
                <script src="./app.js" defer></script>
          </head>
          <body>
            <ul class="parent">
                <li class="child">First Item</li>
               <li class="child">Second Item</li>
                <li class="child">Third Item</li>
             </ul>
         </body>
</html>
Enter fullscreen mode Exit fullscreen mode
const items = document.querySelector("ul")
const newList = document.createElement("li");
newList.textContent = "Fourth Item";
items.appendChild(newList);
Enter fullscreen mode Exit fullscreen mode

In the preceding code, the ul element and stored in a variable items. Then we create a new li element using the createElement method, storing it in a variable newList. We easily add some content to it using the textElement method.

To add newList to items, we use the append method while passing newList as the parameter. The updated list would be updated to;

First Item
Second Item
Third Item
Fourth Item

Removing and Replacing Elements

Just as we can select and insert elements into the DOM, we can also easily remove elements from the DOM using the remove() method.

For example, let us remove the first item from the list with this method. We would first select the first li element using querySelector and store it in a variable firstItem.

const firstItem = document.querySelector("li");
firstItem.remove();
document.querySelector("li");
Enter fullscreen mode Exit fullscreen mode

Using the remove() method, we deleted the first list from the HTML list, which would now be updated to:

Second Item
Third Item

In cases where we want to replace the element and not get rid of them, we can use the replaceWith() method.

const newList = document.createElement("li");
newList.textContent = "Fourth Item";
const firstItem = document.querySelector("li")
firstItem.replaceWith(newList);
Enter fullscreen mode Exit fullscreen mode

The list would be updated to:

Fourth Item               
Second Item
Third Item

Cloning DOM Nodes

We can clone a Node using the cloneNode() method. This would return a brand new node and keep the old node. It takes an optional argument which is a boolean argument that is, either true or false.

By default, it is set at false, and in this case, only the selected element is cloned without any nested element.

COPY

<html>
          <head>
                <title>Cloning DOM Nodes</title>
                <script src="./app.js" defer></script>
          </head>
          <body>
            <ul class="parent">
                <li class="child">First Item</li>
               <li class="child">Second Item</li>
                <li class="child">Third Item</li>
             </ul>
         </body>
</html>
const items = document.querySelector("ul");
const clone = items.cloneNode(false);
console.log(clone);

The output would be

<ul class="parent"> </ul>

When the argument is true, all descendants of the selected element will be cloned.

const items = document.querySelector("ul");
const clone = items.cloneNode(true);
console.log(clone);

The output in the console would be:

         <ul class="parent">
                <li class="child">First Item</li>
               <li class="child">Second Item</li>
                <li class="child">Third Item</li>
           </ul>

Conclusion

In this article, you learned how to use and replicate the Javascript Dom in your project.

If you find this post exciting, find more exciting posts on Learnhub Blog; we write everything tech from Cloud computing to Frontend Dev, Cybersecurity, AI, and Blockchain.

Resource

This article was written by tosynthegeek who is a  Blockchain and Crypto Enthusiast.

Top comments (9)

Collapse
 
efpage profile image
Eckehard • Edited

Creating HTML elements and appending manually to the DOM with the standard HTML-DOM-API is failry complicated and labourious. Currently there are two projects on github, that try to make direct DOM manipulation far easier:

  • VanJS The World's smallest reactive UI framework
  • DML, The Document Makeup Library

Both "frameworks" follow the same simple and most logical approach to provide "tag"-functions: To create an <h1>-element, they provide an h1( ... )-function that create the element and returns the DOM reference. As you can store DOM references in JS-variables, you do not need to use "getElementBy..." to acess the DOM:

let myHeadline = h1("This is a headline")
myHeadline.style.color = "red"
Enter fullscreen mode Exit fullscreen mode

Both "frameworks" follow a slightly different approach, but they show, that it is possible to create complex Web-Applications using direct DOM access.

Collapse
 
bitifet profile image
Joan Miquel Torres

I wouldn't call it "complicated". It's just a low level operation which is there to allow us to implement higher level abstractions.

If you use it for unique and specific tasks, then you are in the right path. On the other hand, if you find yourself repeating the same patterns again and again, then you're not.

BTW, just in case you could be interested in another abstraction for powerful while simple to implement forms: dev.to/bitifet/simplify-web-form-d...

Collapse
 
scofieldidehen profile image
Scofield Idehen

let me take a look, thanks for your feedback.

Collapse
 
prsaya profile image
Prasad Saya • Edited

I was building a web page few days back and I was using the DOM manipulation techniques - selecting, creating and traversing - though I wasn't thinking the terminology. Here is that page: Prasad Saya | Posts. (The page's HTML and JavaScript can be viewed from the browser's View Source).

Collapse
 
scofieldidehen profile image
Scofield Idehen

Really.

Collapse
 
prsaya profile image
Prasad Saya • Edited

It was about reading data from an array of objects where each item is data related to a post (title, date, site, tag, url, description). On a page load this array data is built as a table rows - each row representing a post. Also, appropriate CSS is applied. All this using DOM APIs in JavaScript.

The sample data for a post:

{
            "title": "MySQL Unique Key and not primary key",
            "date": "Feb 15, 2023",
            "site": "https://stackoverflow.com/",
            "tag_": { "data": "database", "display": "database" },
            "url": "https://stackoverflow.com/questions/75454687/mysql-unique-key-and-not-primary-key/75455977#75455977",
            "description": "This is a clarification about a table's primary key column and how to drop the constraint."
},
Enter fullscreen mode Exit fullscreen mode

And, it is rendered as:

Image of a post as rendered in the page

Collapse
 
armanrahman profile image
Arman Rahman

Informative ❤

Collapse
 
scofieldidehen profile image
Scofield Idehen

Thanks.

Collapse
 
onlinemsr profile image
Raja MSR

Thank you for this informative and clear blog post on DOM manipulation with JavaScript.