DOM Traversing in JavaScript: Navigating the Document Object Model


DOM traversing in JavaScript refers to the process of navigating the Document Object Model (DOM) to access and manipulate elements and their properties within an HTML document. The DOM is a tree-like structure that represents the structure of an HTML document, where each element is represented by a node in the tree.

There are several methods in JavaScript that allow for DOM traversing, including:

  1. parentNode and childNodes: These properties allow you to access the parent and child nodes of an element, respectively.
  2. nextSibling and previousSibling: These properties allow you to access the next and previous sibling nodes of an element.
  3. firstChild and lastChild: These properties allow you to access the first and last child nodes of an element.
  4. querySelector and querySelectorAll: These methods allow you to search for elements within the DOM using CSS-style selectors.
  5. getElementById, getElementsByClassName, and getElementsByTagName: These methods allow you to access elements in the DOM based on their ID, class name, or tag name, respectively.

Using these methods and properties, you can traverse the DOM to locate specific elements and manipulate their properties, such as changing their text content or modifying their style. DOM traversing is a powerful tool for creating dynamic and interactive web pages in JavaScript.

parentNode

In JavaScript, a parent node refers to the node that is immediately higher in the DOM (Document Object Model) hierarchy relative to another node.

In other words, if a particular node has child nodes, then its parent node is the immediate node that contains it. For example, consider the following HTML code:

<div>
   <h2>Sample Title</h2>
   <p>This is Paragraph</p>
</div>

In this code, the parent node is the div element, which contains two child nodes, both of which are h2 and p elements.

In JavaScript, you can access the parent node of an element using the parentNode property. For example, to access the parent node of the second child p element in the example above, you could use the following code:

const para = document.getElementsByTagName("p");
console.log(para);
const parent = para[0].parentNode;
console.log(parent);
parent.style.backgroundColor = "palegreen";
parent.style.padding = "10px";

const h1 = document.getElementsByTagName("h1");
console.log(h1);
const parent_h1 = h1[0].parentNode;
parent_h1.style.backgroundColor = "palevioletred";
parent_h1.style.padding = "10px";

Example for parentNode Structure

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <section>
      <h1>This is Heading</h1>
      <div>
        <h2>Sample Title</h2>
        <p>This is Paragraph</p>
      </div>
    </section>
  </body>
</html>
parent node


First and Last Child

In JavaScript, the terms "first child" and "last child" typically refer to the first and last elements of a parent element's child node list.

To understand this concept, it's helpful to first understand the Document Object Model (DOM), which is a programming interface for web documents. The DOM represents the page as a tree-like structure, where each element is a node in the tree.

child method

In the context of the DOM, a "parent element" is an element that contains one or more child elements. For example, if you have an HTML document with a <div> element containing several other elements, the <div> element would be the parent element, and the other elements would be its child elements.

Using JavaScript, you can access the child nodes of a parent element using the childNodes property. This property returns an array-like object called a NodeList, which contains all of the child nodes of the parent element, including any text nodes or comments.

To get the first child element of a parent element, you can use the firstElementChild property. This property returns the first child element of the parent element, or null if the parent element has no child elements.

Similarly, to get the last child element of a parent element, you can use the lastElementChild property. This property returns the last child element of the parent element, or null if the parent element has no child elements.



Here's an example that demonstrates how to get the first and last child elements of a parent element:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <section>
      <h1>This is Heading</h1>
      <div>
        <h2>Sample Title</h2>
        <p>This is Paragraph</p>
      </div>
    </section>
    <script src="script.js"></script>
  </body>
</html>

script.js

//firstChild
const firstChild = parent.firstChild;
console.log(firstChild);
//lastChild
const lastChild = parent.lastChild;
console.log(lastChild);

//firstElementChild
const firstElementChild = parent.firstElementChild;
console.log(firstElementChild);
firstElementChild.style.color = "blue";
//lastElementChild
const lastElementChild = parent.lastElementChild;
console.log(lastElementChild);
lastElementChild.style.color = "red";

const section = document.getElementsByTagName("section")[0];
console.log(section.firstChild);
console.log(section.firstElementChild);
console.log(section.lastChild);
console.log(section.lastElementChild);

console.log(h1[0].firstChild);
console.log(h1[0].firstElementChild);
console.log(h1[0].lastChild);
console.log(h1[0].lastElementChild);
//children
const div = document.getElementsByTagName("div")[0];
console.log(div);
console.log(div.children[0]);
console.log(div.children[1]);
console.log(div.childElementCount);
console.log(div.childNodes);

Siblings

In JavaScript, the DOM (Document Object Model) represents the HTML elements of a web page as a tree-like structure. DOM siblings refer to the HTML elements that share the same parent element in the DOM tree.

For example, consider the following HTML code:

<div>
   <h2>Sample Title</h2>
   <p>This is Paragraph</p>
</div>

In this code, the parent node is the div element, which contains two child nodes, both of which are h2 and p elements.In other words, they are all direct children of the div element.

We can use JavaScript to access these sibling elements using various DOM methods. For example, we can use the parentNode property to get the parent element of any of the child elements:

We can also use the previousSibling and nextSibling properties to get the siblings of an element. For example, we can use nextSibling to get the next sibling of the first element

It's important to note that the previousSibling and nextSibling properties return all types of nodes, not just HTML elements. This means that we may need to use additional logic to filter out non-element nodes.

In summary, DOM siblings in JavaScript refer to the HTML elements that share the same parent element in the DOM tree. We can use various DOM methods to access and manipulate these sibling elements.

Siblings


Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <section>
      <h1>This is Heading</h1>
      <div>
        <h2>Sample Title</h2>
        <p>This is Paragraph</p>
      </div>
    </section>
    <script src="script.js"></script>
  </body>
</html>

script.js

//Siblings
const p = document.getElementsByTagName("p")[0];
console.log(p);
console.log(p.previousSibling);
console.log(p.previousElementSibling);

const h2 = document.getElementsByTagName("h2")[0];
console.log(h2);
console.log(h2.nextSibling);
console.log(h2.nextElementSibling);

const section = document.getElementsByTagName("section")[0];
console.log(section);
console.log(section.nextSibling);
console.log(section.nextElementSibling);
console.log(section.previousSibling);
console.log(section.previousElementSibling);

Closest

In JavaScript, the closest() method is a DOM method that allows you to traverse up the DOM tree from a specific element and find the closest ancestor element that matches a specified CSS selector. This method can be particularly useful when you need to find a specific parent element that contains a certain child element.

Here is the syntax for using the closest() method:

element.closest(selector);

Here, element is the element you want to start the search from, and selector is a CSS selector that specifies the type of element you are looking for. The closest() method returns the closest ancestor element of element that matches the selector, or null if no matching element is found.

For example, consider the following HTML code:

<div>
   <h2>Sample Title</h2>
   <p>This is Paragraph</p>
</div>

If you want to find the closest ancestor element of the <p> element that has the class "parent", you can use the closest() method like this:

const h1_tag = document.querySelector("h1");
console.log(h1_tag);
const section = h1_tag.closest("section");
console.log(section);
section.style.background = "purple";
section.style.color = "white";
section.style.padding = "10px";

This JavaScript code first selects the first <h1> element in the HTML document using the querySelector() method and assigns it to the h1_tag variable.Then, it uses the closest() method to find the closest ancestor element of the h1_tag that is a <section> element and assigns it to the section variable.

Overall, this code demonstrates how to use the closest() method to find an ancestor element based on its tag name and how to use the style property to modify the CSS styles of an element in JavaScript.

List of Programs


JS Practical Questions & Answers


JS Practical Project