DOM Manipulation

Dilip AsdeoDilip Asdeo
4 min read

1. Introduction: The Dynamic Web with DOM

The Document Object Model (DOM) is the bridge between HTML and JavaScript. It's a platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of documents.

Imagine the DOM as a tree-like representation of your HTML, where each HTML element is a node. This allows JavaScript to traverse, modify, and create elements, making web pages interactive. Understanding DOM manipulation is fundamental for any web developer.

2. Understanding the DOM: The Tree Structure

The DOM represents HTML as a tree. For example:

<!DOCTYPE html>
<html>
<head>
    <title>My Page</title>
</head>
<body>
    <div id="container">
        <p class="text">Hello, DOM!</p>
        <ul>
            <li>Item 1</li>
            <li>Item 2</li>
        </ul>
    </div>
</body>
</html>

This translates to a DOM tree (simplified):

Document
  |
  <html>
    |-- <head>
    |     |-- <title>
    |         |-- "My Page"
    |-- <body>
        |-- <div id="container">
        |     |-- <p class="text">
        |     |     |-- "Hello, DOM!"
        |     |-- <ul>
        |         |-- <li>
        |         |     |-- "Item 1"
        |         |-- <li>
        |         |     |-- "Item 2"

The document object is the root of the DOM tree.

console.log(document); // Prints the entire document object
console.log(document.documentElement); // Prints the <html> element
console.log(document.head); // Prints the <head> element
console.log(document.body); // Prints the <body> element

3. DOM Manipulation: Selecting Elements

  • getElementById(): Selects a single element by its unique ID.

      const container = document.getElementById("container");
      console.log(container);
    
  • getElementsByClassName(): Selects all elements with a specific class name (returns an HTMLCollection).

      const textElements = document.getElementsByClassName("text");
      console.log(textElements);
      for (let element of textElements) {
          console.log(element.textContent);
      }
    
  • getElementsByTagName(): Selects all elements with a specific tag name (returns an HTMLCollection).

      const listItems = document.getElementsByTagName("li");
      console.log(listItems);
    
  • querySelector(): Selects the first element that matches a CSS selector.

      const firstListItem = document.querySelector("ul li");
      console.log(firstListItem);
      const containerDiv = document.querySelector("#container");
      console.log(containerDiv);
    
  • querySelectorAll(): Selects all elements that match a CSS selector (returns a NodeList).

      const allListItems = document.querySelectorAll("ul li");
      console.log(allListItems);
      allListItems.forEach(item => console.log(item.textContent));
    

4. Modifying Element Content and Attributes

  • textContent: Gets or sets the text content of an element.

      const paragraph = document.querySelector(".text");
      paragraph.textContent = "New text content!";
    
  • innerHTML: Gets or sets the HTML content of an element.

      const container = document.getElementById("container");
      container.innerHTML = "<p>New paragraph inside container</p>";
    
  • setAttribute() / getAttribute(): Sets or gets the value of an attribute.

      const link = document.createElement("a");
      link.setAttribute("href", "https://example.com");
      link.textContent = "Visit Example";
      document.body.appendChild(link);
      console.log(link.getAttribute("href"));
    

5. Changing Styles Dynamically

  • style property: Modifies inline styles.

      const paragraph = document.querySelector(".text");
      paragraph.style.color = "red";
      paragraph.style.fontSize = "18px";
    
  • classList: Manipulates CSS classes.

      const paragraph = document.querySelector(".text");
      paragraph.classList.add("highlight");
      paragraph.classList.remove("text");
      paragraph.classList.toggle("active"); // Toggles the 'active' class
    
      .highlight {
          background-color: yellow;
      }
      .active {
        font-weight: bold;
      }
    

6. Creating and Removing Elements

  • document.createElement(): Creates a new element.

      const newParagraph = document.createElement("p");
      newParagraph.textContent = "Dynamically created paragraph.";
    
  • appendChild(): Appends a child element to a parent element.

      document.body.appendChild(newParagraph);
    
  • insertBefore(): Inserts a node before a reference node as a child of a specified parent node.

      const ul = document.querySelector('ul');
      const newLi = document.createElement('li');
      newLi.textContent = "Inserted Item";
      ul.insertBefore(newLi, ul.firstChild);
    
  • removeChild(): Removes a child element from a parent element.

      document.body.removeChild(newParagraph);
    
  • remove(): Removes the element from the DOM.

      const listItemToRemove = document.querySelector("ul li:last-child");
      listItemToRemove.remove();
    

7. Traversing the DOM

  • parentNode: Gets the parent node of an element.

      const listItem = document.querySelector("li");
      console.log(listItem.parentNode);
    
  • childNodes: Gets a NodeList of child nodes.

      const ul = document.querySelector("ul");
      console.log(ul.childNodes);
    
  • firstChild / lastChild: Gets the first or last child node.

      console.log(ul.firstChild);
      console.log(ul.lastChild);
    
  • nextSibling / previousSibling: Gets the next or previous sibling node.

      console.log(listItem.nextSibling);
      console.log(listItem.previousSibling);
    

8. Events and Event Listeners

  • addEventListener(): Attaches an event handler to an element.
const button = document.createElement("button");
button.textContent = "Click Me";
document.body.appendChild(button);

button.addEventListener("click", () => {
    alert("Button clicked!");
});

By mastering the fundamentals of DOM manipulation, you can create dynamic and interactive web experiences. Practice these techniques, experiment with different scenarios, and you'll be well on your way to building engaging web applications.

1
Subscribe to my newsletter

Read articles from Dilip Asdeo directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Dilip Asdeo
Dilip Asdeo