JS HTML DOM

The HTML DOM (Document Object Model) is a programming interface for HTML documents. It defines the logical structure of documents and the way a document is accessed and manipulated. Essentially, when a web page is loaded, the browser creates a DOM of the page. This DOM is represented as a tree structure, where each HTML element, attribute, and even text content becomes a “node” in the tree.

Think of it like this: your HTML code is a static blueprint. The DOM is the live, interactive representation of that blueprint that JavaScript can talk to.

The DOM as a Tree Structure

Consider this simple HTML:

HTML

<!DOCTYPE html>
<html>
<head>
    <title>My Page</title>
</head>
<body>
    <h1 id="main-title">Welcome</h1>
    <p class="intro">Hello, <span>world</span>!</p>
    <button>Change Text</button>
</body>
</html>

The browser interprets this into a DOM tree that looks something like this:

  • Document (the root of everything)
    • html (element node)
      • head (element node)
        • title (element node)
          • “My Page” (text node)
      • body (element node)
        • h1 (element node)
          • id="main-title" (attribute node)
          • “Welcome” (text node)
        • p (element node)
          • class="intro" (attribute node)
          • “Hello, ” (text node)
          • span (element node)
            • “world” (text node)
          • “!” (text node)
        • button (element node)
          • “Change Text” (text node)

Every node in this tree is an object, and these objects expose methods and properties that JavaScript can use to interact with the web page.

Key DOM Concepts for JavaScript

  1. Nodes:
    • Element Nodes: Represent HTML tags (e.g., <div>, <p>, <h1>). These are the most common nodes you’ll interact with.
    • Text Nodes: Represent the actual text content within an element.
    • Attribute Nodes: Represent attributes of HTML elements (e.g., id="main-title", class="intro"). While attributes are part of element objects, they can also be treated as separate nodes.
    • Document Node: The root node (document object) that represents the entire HTML document.
    • Window Object: Although not strictly part of the DOM, the window object is the global object in the browser environment and contains the document object.
  2. Accessing/Selecting Elements (Nodes): JavaScript provides several methods on the document object to select elements:
    • document.getElementById('idName'): Returns a single element object that has the specified ID. This is the fastest method and should be used when an element has a unique ID.JavaScriptconst titleElement = document.getElementById('main-title'); console.log(titleElement.textContent); // Output: Welcome
    • document.getElementsByClassName('className'): Returns an HTMLCollection (live list) of all elements with the specified class name.JavaScriptconst paragraphs = document.getElementsByClassName('intro'); console.log(paragraphs[0].textContent); // Output: Hello, world!
    • document.getElementsByTagName('tagName'): Returns an HTMLCollection (live list) of all elements with the specified tag name.JavaScriptconst allParagraphs = document.getElementsByTagName('p'); console.log(allParagraphs.length); // Output: 1 (in our example HTML)
    • document.querySelector('CSS-selector'): Returns the first element that matches the specified CSS selector. This is very versatile.JavaScriptconst firstParagraph = document.querySelector('p.intro'); const firstButton = document.querySelector('button');
    • document.querySelectorAll('CSS-selector'): Returns a NodeList (static list) of all elements that match the specified CSS selector.JavaScriptconst allElements = document.querySelectorAll('p, h1'); // Selects all <p> and <h1>

Manipulating Elements

Once you have a reference to an element node, you can modify its properties or content.

  1. Changing Content:
    • element.textContent: Gets or sets the text content of the element (plain text, HTML tags are escaped).
    • element.innerHTML: Gets or sets the HTML content of the element (HTML tags are parsed). Use with caution to prevent XSS vulnerabilities if you’re inserting user-supplied content.
    JavaScriptconst titleElement = document.getElementById('main-title'); titleElement.textContent = 'New Title from JS!'; // Changes text titleElement.innerHTML = 'Welcome to <em>my</em> Page!'; // Adds emphasis tag
  2. Changing Attributes:
    • element.setAttribute('attributeName', 'value'): Sets the value of an attribute.
    • element.getAttribute('attributeName'): Gets the value of an attribute.
    • element.removeAttribute('attributeName'): Removes an attribute.
    • element.id, element.className, element.src, element.href: Many common attributes can be accessed directly as properties of the element object.
    JavaScriptconst myButton = document.querySelector('button'); myButton.setAttribute('data-action', 'submit'); console.log(myButton.getAttribute('data-action')); // Output: submit // Change a class directly const introParagraph = document.querySelector('.intro'); introParagraph.className = 'highlight-text'; // Overwrites existing classes // For safer class manipulation, use classList: introParagraph.classList.add('new-class'); introParagraph.classList.remove('intro'); introParagraph.classList.toggle('active'); // Adds if not present, removes if present
  3. Changing CSS Styles:
    • element.style.propertyName: Directly sets inline CSS properties. Use camelCase for multi-word CSS properties (e.g., backgroundColor for background-color).
    JavaScripttitleElement.style.color = 'blue'; introParagraph.style.fontSize = '18px';
  4. Creating and Deleting Elements:
    • document.createElement('tagName'): Creates a new element node.
    • document.createTextNode('text'): Creates a new text node.
    • parentElement.appendChild(childElement): Adds a new child element to the end of a parent.
    • parentElement.insertBefore(newElement, referenceElement): Inserts a new element before a specified reference element.
    • parentElement.removeChild(childElement): Removes a child element from a parent.
    JavaScriptconst newDiv = document.createElement('div'); newDiv.textContent = 'I am a new div!'; document.body.appendChild(newDiv); // Add to the end of the body const existingButton = document.querySelector('button'); existingButton.remove(); // Removes the button directly (modern way) // Or: existingButton.parentNode.removeChild(existingButton); // Older, more verbose way

Events

The DOM is central to handling user interactions (events). You attach “event listeners” to elements to execute JavaScript code when a specific event occurs (e.g., click, mouseover, keypress, form submit).

JavaScript

document.addEventListener('DOMContentLoaded', () => {
    const mainTitle = document.getElementById('main-title');
    mainTitle.addEventListener('click', () => {
        alert('Title clicked!');
        mainTitle.style.color = 'red';
    });
});

Understanding and effectively utilizing the HTML DOM is fundamental to creating dynamic and interactive web pages with JavaScript. It’s the bridge between your static HTML structure and the powerful programmatic capabilities of JavaScript.

Share the Post:

Related Posts