DEV Community

Parthipan M
Parthipan M

Posted on

DOM in Java Script

Document Object Model

The Document Object Model (DOM) is a programming interface provided by web browsers that represents an HTML or XML document as a tree of objects, allowing JavaScript to dynamically access, modify, and interact with the page's content, structure, and style.

Example:

<html>
  <body>
    <h1>Hello Parthipan</h1>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

The DOM Tree Structure:

  • The Document: The root or "owner" of the entire tree. In JavaScript, you access this via the global document object.

  • Elements: The HTML tags themselves (like <body>, <div>, <h1>, or <button>).

  • Attributes: Properties inside those tags (like href, src, or class).

  • Text: The actual text written inside your tags (e.g., "Click Me").

Accessing HTML Elements:

The HTML DOM can be used to access HTML elements.

The most common way to access an HTML element is to use the id of the element:

Example:

<html>
<body>
    <h1 id="head">DOM</h1>
    <div class="para">parthipan</div>
    <div class="para">Tony</div>
    <div class="para">antony</div>
    <div class="para">antony</div>
    <button onclick="changeContent()">changeContent</button>
    <script>
    // const changeContent = () => {
    //     document.getElementById("head").textContent = "Hello parthipan"
    //     document.getElementById("head").textContent = "Hello tony"
    //     document.getElementById("head").textContent = "Hello antony"
    //     document.getElementById("head").textContent = "Hello jaisuriya"
    // };
    // console.log(document.getElementById("head").textContent);
const divs = document.getElementsByClassName("para")
for (let i=0; i<divs.length; i++){
    divs[i].style ="color:red";
}

    </script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

In the example above, thegetElementById method used id="head" to find the element.

  • id="head" is an HTML property

  • getElementById() is a DOM Method

  • innerHTML is a DOM Property

Top comments (0)