DOM Manipulation

Introduction to the DOM

The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of a webpage as a tree of objects, allowing developers to interact with and manipulate the content, structure, and styles of a webpage dynamically.

Understanding DOM Structure

The DOM represents an HTML document as a tree of nodes. Each element, attribute, and piece of text is a node in this tree. For example:

<html>
  <head>
    <title>Page Title</title>
  </head>
  <body>
    <h1>Heading</h1>
    <p>Paragraph</p>
  </body>
</html>

This structure is represented in the DOM as a hierarchy of nodes, with html as the root node.

Selecting Elements

To interact with elements in the DOM, you first need to select them. Common methods include:

  • document.getElementById("id"): Selects an element by its ID.
  • document.querySelector("selector"): Selects the first element matching a CSS selector.
  • document.querySelectorAll("selector"): Selects all elements matching a CSS selector.

Example:

const heading = document.getElementById("main-heading");
const paragraphs = document.querySelectorAll("p");

Manipulating Elements

Once elements are selected, you can manipulate their content, attributes, and styles. Examples include:

  • Changing content: element.textContent = "New Content";
  • Modifying attributes: element.setAttribute("class", "new-class");
  • Updating styles: element.style.color = "blue";

Example:

const heading = document.getElementById("main-heading");
heading.textContent = "Updated Heading";
heading.style.color = "red";

Event Handling

Events allow you to respond to user interactions such as clicks, key presses, or mouse movements. Use addEventListener to attach event listeners to elements.

Example:

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

Best Practices

  • Minimize direct DOM manipulation to improve performance.
  • Use event delegation for better efficiency with dynamic elements.
  • Keep your JavaScript code modular and reusable.