DEV Community

VINOTH
VINOTH

Posted on

Document Object Model (DOM)

The Document Object Model (DOM) connects web pages to scripts or programming languages by representing the structure of a document—such as the HTML representing a web page—in memory. Usually it refers to JavaScript, even though modeling HTML, SVG, or XML documents as objects are not part of the core JavaScript language.

Refer:
https://www.w3schools.com/js/img_htmltree_800.svg

Core Concepts

  1. The DOM Tree: The HTML document becomes a hierarchy of nodes.
  2. Nodes: Everything is a node (elements, text, comments).
  3. Elements: HTML tags(like or

    )converted into JavaScript objects.

1. Selecting Elements

To manipulate an element, you must first find it in the DOM tree.

  1. document.getElementById('id') — Finds a single element by its unique ID.
  2. document.getElementsByClassName('class') — Returns a live collection of elements with that class.
  3. document.getElementsByTagName('tag') — Returns a live collection of elements with that tag name.
  4. document.querySelector('selector') — Returns the first element matching a CSS selector.
  5. document.querySelectorAll('selector') — Returns a static NodeList of all elements matching a CSS selector.

2. Modifying Content and Attributes
Once selected, you can alter the text, HTML contents, or attributes of an element.

  1. element.textContent — Gets or sets the text inside an element (ignores HTML tags).
  2. element.innerHTML — Gets or sets the HTML markup inside an element.
  3. element.setAttribute('attr', 'value') — Adds or updates an attribute (e.g., src, href).
  4. element.getAttribute('attr') — Retrieves the value of a specified attribute.
  5. element.removeAttribute('attr') — Removes an attribute from the element.

Quick Example

`

<h1 id="welcome">
    welcome.....!!!!!
</h1>

<button onclick="getTxt()"> change the inside </button>
<script>
    function getTxt() {
        const ele = document.getElementById("welcome");

        if (ele.innerText == "welcome.....!!!!!") {
            ele.innerText = "ViNo";
        } else {
            ele.innerText = "welcome.....!!!!!"
        }
        console.log(ele.innerText);
    }



</script>
Enter fullscreen mode Exit fullscreen mode

`

Top comments (0)