DEV Community

Sidra Maqbool
Sidra Maqbool

Posted on

Understanding DOM Nodes: A Comprehensive Guide with Example

The Document Object Model (DOM) is a tree-like structure that represents the HTML elements in a web page. The nodes of the DOM are the individual elements, attributes, and text within the HTML code. Understanding the different types of DOM nodes is crucial when working with JavaScript and manipulating web pages.

Here are the different types of nodes in the DOM:

  1. Document Node: This is the top-level node in the DOM and represents the entire HTML document.
  2. Element Node: This represents an HTML element, such as <div>, <p>, <ul>, etc.
  3. Attribute Node: This represents an attribute of an HTML element, such as id, class, src, etc.
  4. Text Node: This represents the actual text within an HTML element.

Let's take a look at an example to see how these nodes work together. Consider the following HTML code:

<!DOCTYPE html>
<html>
  <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>DOM Node Example</title>
  </head>
  <body>
    <div id="myDiv">
      <p>Hello World!</p>
      <ul>
        <li>Item 1</li>
        <li>Item 2</li>
      </ul>
    </div>
  </body>
</html>

Enter fullscreen mode Exit fullscreen mode

In this example, we have several different types of DOM nodes:

The document node is represented by the entire HTML code.

  • The <div> element is an example of an element node, with an attribute node for id.
  • The <p> element is another example of an element node, with a text node containing the actual text "Hello World!".
  • The <ul> element is an element node, with two child element nodes for the list items.
  • The <li> elements are also element nodes, with text nodes containing the text "Item 1" and "Item 2", respectively.

Understanding the different types of DOM nodes and how they relate to each other is essential when manipulating web pages with JavaScript. By accessing and manipulating these nodes, we can dynamically update the content and appearance of web pages to create interactive and engaging user experiences.

To see a working example of DOM Nodes in action, check out my GitHub repository: https://github.com/SidraMaq/DOM/tree/main/DOM-Nodes.

Thanks for reading! I hope you found this post informative and helpful. If you have any questions or feedback, please feel free to leave a comment below. And don't forget to check out my GitHub repository for working example of DOM Nodes.

Top comments (0)