Understanding DOM Manipulation with JavaScript
Tags: webdev, javascript, react, programming
Published: 2023-07-07 03:20:11

<p data-pm-slice="1 1 []">Document Object Model or DOM is a programming interface that allows JavaScript to manipulate elements in an HTML document.</p>
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.
<h2><strong>Selecting Elements in the DOM</strong></h2>
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:
<h3><strong>getElementById()</strong></h3>
<code>document.getElementById()</code> access elements with a specific id that matches the one mentioned in the string.
```javascript
<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>
```
```javascript
const element = document.getElementById("heading");
```
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 <code>document.getElementById()</code> method returns the first element it encounters. In cases where the ID given does not exist, it returns null.
<h3><strong>getElementByClassName()</strong></h3>
<code>document.getElementByClassName()</code> 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 <code>document.getElementById()</code>, <code>document.getElementByClassName()</code> 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 <code>getElementsByClassName()</code> works with HTML elements:
```javascript
<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>
```
```javascript
const items = document.getElementsByClassName("item");
```
In the code snippet, the first element with the class <code>item</code> is selected and stored in a variable <code>items</code>.
<h3><strong>querySelector()</strong></h3>
<code>document.querySelector()</code> is a method that allows you to select the first element that matches the CSS selector.
```javascript
<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>
```
```javascript
const items = document.querySelector("li");
console.log(items);
```
In this code, the js script uses the <code>document.querySelector("li")</code> to select the first li element.
<h2><strong>Selecting Multiple Elements in the DOM</strong></h2>
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:
<h3><strong>querySelectorAll()</strong></h3>
<code>document.querySelectorAll()</code> is used to select all elements with a CSS selector. It returns a static <code>NodeList</code> of elements. This means it does not change or reflect when tag names are deleted or added.
```javascript
<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>
```
```javascript
const items = document.querySelectorAll("li");
console.log(items);
```
From the above JavaScript code, we can easily select all the elements with the <code>li</code> CSS selector.

<strong>P S:</strong> This should not be confused with <code>querySelector()</code>. <code>querySelector()</code> selects just the first element with a specific CSS selector. While <code>querySelectorAll()</code> selects all elements with a specific CSS selector
<h3><strong>getElementByTagName()</strong></h3>
<code>document.getElementByTagName()</code> 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,
```javascript
<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>
```
```javascript
const headings = document.getElementsByTagName("h1");
console.log(headings);
```
In the JavaScript code snippet, all of the elements with the tag name <code>h1</code> are selected and displayed.
<h2><strong>Traversing the DOM</strong></h2>
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:
<ul>
 	<li>Upwards</li>
 	<li>Sideways</li>
 	<li>Downwards</li>
</ul>
<h3><strong>Upward traversing</strong></h3>
This involves accessing a child element from its parent element or ancestors. The most common method used for upward traversing is <code>parentElement()</code>.
<h4><strong>Using parentElemet or parentNode</strong></h4>
You can traverse up the DOM using <code>parentElement()</code> or <code>parentNode()</code>. This lets you access the element/node that encloses the current element.
```javascript
<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>
```
```javascript
const item = document.querySelector(".child");
const parentN = item.parentNode
const parentEl = item.parentElement
console.log(parentN);
console.log(parentEl)
```
In the JavaScript code snippet, the first element with the class <code>child</code> is selected and stored in a variable <code>item</code>. Now, we can use the parentNode and parentElement methods to access this element's parent node and parent element.
<h3><strong>Sideways traversing</strong></h3>
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
<h4><strong>Using nextElementSibling and previousElementSibling</strong></h4>
When navigating the DOM sideways we can select the next element using <code>nextElementSibling</code> and select the previous element using <code>previousElementSibling</code>.
```javascript
<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>
```
```javascript
const firstItem = document.querySelector("li");
console.log(firstItem.nextElementSibling);
const secondItem = document.querySelectorAll("li")[1];
console.log(secondItem.previousElementSibling);
```
This might be a bit confusing so let’s break down the code:

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

<strong>Line 2</strong> we easily access the next element of the <code>firstItem</code> using the <code>nextElementSibling</code> method.

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

<strong>Line 4</strong> we easily access the previous element of secondItem using the <code>previousElementSibling()</code> method.

<strong><mark>PS</mark></strong><mark>:</mark> This should give further clarity on the differences between <code>querySelector()</code> and <code>querySelectorAll()</code> and how they are used.
<h3><strong>Downward Traversing</strong></h3>
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.
<h4><strong>Selecting children Element</strong></h4>
In navigating the DOM downwards, we can use the children property to select direct descendants of the current element.
```javascript 
<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>
```
```javascript
<pre><code class="language-javascript">const parent = document.querySelector(".parent");
const children = parent.children;
```
In the JavaScript code snippet, the first element with the class <code>parent</code> is selected and stored in a variable <code>parent</code>. Now, we can use the children method to access the element's descendants.
<h2><strong>Creating HTML Elements in JavaScript</strong></h2>
We can create new HTML elements from a Javascript code using the <code>document.createElement()</code> method. This method takes an argument of the type of element we want to create.

For example:
```javascript
<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>
```
We can use the <code>createElement()</code> method to create a new <code>&lt;li&gt;</code> element in JavaScript code.
<pre><code class="language-javascript">const newList = document.createElement("li");
</code></pre>
Now, we can easily add some content to the <code>newList</code> using the <code>textContent</code> method;
```javascript
const newList = document.createElement("li");
newList.textContent = "Fourth Item";
console.log(newList)
```
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.
<h2>Inserting Elements</h2>
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 <code>append()</code> or <code>appendChild()</code> method. For example, we would use one of these to insert a new list as the Fourth Item in the HTML code.
```javascript
<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>
```
```javascript
const items = document.querySelector("ul")
const newList = document.createElement("li");
newList.textContent = "Fourth Item";
items.appendChild(newList);
```
In the preceding code, the <code>ul</code> element and stored in a variable <code>items</code>. Then we create a new <code>li</code> element using the createElement method, storing it in a variable newList. We easily add some content to it using the <code>textElement</code> method.

To add <code>newList</code> to items, we use the append method while passing <code>newList</code> as the parameter. The updated list would be updated to;
<pre><code class="language-javascript">First Item
Second Item
Third Item
Fourth Item
</code></pre>
<h2>Removing and Replacing Elements</h2>
Just as we can select and insert elements into the DOM, we can also easily remove elements from the DOM using the <code>remove()</code> method.

For example, let us remove the first item from the list with this method. We would first select the first <code>li</code> element using querySelector and store it in a variable <code>firstItem</code>.
```javascript
const firstItem = document.querySelector("li");
firstItem.remove();
document.querySelector("li");
```
Using the <code>remove()</code> method, we deleted the first list from the HTML list, which would now be updated to:
<pre><code class="language-javascript">Second Item
Third Item
</code></pre>
In cases where we want to replace the element and not get rid of them, we can use the <code>replaceWith()</code> method.
```javascript
const newList = document.createElement("li");
newList.textContent = "Fourth Item";
const firstItem = document.querySelector("li")
firstItem.replaceWith(newList);
```
The list would be updated to:
<pre><code class="language-javascript">Fourth Item               
Second Item
Third Item
</code></pre>
<h1>Cloning DOM Nodes</h1>
We can clone a Node using the <code>cloneNode()</code> 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.

<strong>COPY</strong>
<pre><code class="language-javascript">&lt;html&gt;
          &lt;head&gt;
                &lt;title&gt;Cloning DOM Nodes&lt;/title&gt;
                &lt;script src="./app.js" defer&gt;&lt;/script&gt;
          &lt;/head&gt;
          &lt;body&gt;
            &lt;ul class="parent"&gt;
                &lt;li class="child"&gt;First Item&lt;/li&gt;
               &lt;li class="child"&gt;Second Item&lt;/li&gt;
                &lt;li class="child"&gt;Third Item&lt;/li&gt;
             &lt;/ul&gt;
         &lt;/body&gt;
&lt;/html&gt;
</code></pre>
<pre><code class="language-javascript">const items = document.querySelector("ul");
const clone = items.cloneNode(false);
console.log(clone);
</code></pre>
The output would be
<pre><code class="language-javascript">&lt;ul class="parent"&gt; &lt;/ul&gt;
</code></pre>
When the argument is true, all descendants of the selected element will be cloned.
<pre><code class="language-javascript">const items = document.querySelector("ul");
const clone = items.cloneNode(true);
console.log(clone);
</code></pre>
The output in the console would be:
<pre><code class="language-javascript">         &lt;ul class="parent"&gt;
                &lt;li class="child"&gt;First Item&lt;/li&gt;
               &lt;li class="child"&gt;Second Item&lt;/li&gt;
                &lt;li class="child"&gt;Third Item&lt;/li&gt;
           &lt;/ul&gt;</code></pre>
<h3>Conclusion</h3>
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 <a class="attrlink" href="http://blog.learnhub.africa/" target="_blank" rel="noopener noreferrer nofollow">Learnhub Blog</a>; we write everything tech from <a class="attrlink" href="https://blog.learnhub.africa/category/cloud-computing/" target="_blank" rel="noopener noreferrer nofollow">Cloud computing</a> to <a class="attrlink" href="https://blog.learnhub.africa/category/frontend/" target="_blank" rel="noopener noreferrer nofollow">Frontend Dev</a>, <a class="attrlink" href="https://blog.learnhub.africa/category/security/" target="_blank" rel="noopener noreferrer nofollow">Cybersecurity</a>, <a class="attrlink" href="https://blog.learnhub.africa/category/data-science/" target="_blank" rel="noopener noreferrer nofollow">AI</a>, and <a class="attrlink" href="https://blog.learnhub.africa/category/blockchain/" target="_blank" rel="noopener noreferrer nofollow">Blockchain</a>.
<h3>Resource</h3>
<ul>
 	<li><a href="https://blog.learnhub.africa/2023/06/08/4-javascript-email-frameworks-nodemailer-sendgrid-smtp-js-and-mailgun/" target="_blank" rel="noopener noreferrer nofollow">Javascript Email with Nodemailer</a></li>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/01/18/how-to-send-an-email-in-node-js-using-nodemailer/" target="_blank" rel="noopener noreferrer nofollow">How to send an email in node.js using nodemailer</a></li>
 	<li><a class="attrlink" href="https://www.w3schools.com/js/js_arrays.asp" target="_blank" rel="noopener noreferrer nofollow">Javascript Array method</a></li>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/05/09/20-best-javascript-frameworks-for-2023/" target="_blank" rel="noopener noreferrer nofollow">20 Best React JavaScript Frameworks For 2023</a></li>
</ul>
This article was written by <a href="https://hashnode.com/@tosynthegeek">tosynthegeek</a> who is a <strong> </strong>Blockchain and Crypto Enthusiast.