JavaScript DOM Manipulation

What is the DOM?

The Document Object Model (DOM) is the structure of your webpage represented as a tree of objects. Each HTML element becomes a node that JavaScript can access and manipulate.

For example, <p>Hello</p> becomes a p element node in the DOM tree.

Accessing Elements

const header = document.getElementById("main-header");
const buttons = document.getElementsByClassName("btn");
const links = document.querySelectorAll("a");

getElementById is the fastest, but querySelector is more flexible and supports CSS selectors.

Changing Content and Attributes

document.getElementById("greeting").innerHTML = "Hello, JavaScript!";
document.querySelector("img").setAttribute("src", "new-image.png");

Use innerHTML to inject HTML, textContent for plain text, and setAttribute() to change element attributes.

Changing Style

document.getElementById("box").style.backgroundColor = "lightblue";

Styles can be adjusted directly through the style property or manipulated via class changes using element.classList.

Creating and Removing Elements

const newDiv = document.createElement("div");
newDiv.textContent = "I’m new here!";
document.body.appendChild(newDiv);

const removeMe = document.getElementById("remove-this");
removeMe.remove();

This allows dynamic content generation or removal based on user interaction or logic.

Best Practices

  • Use document.addEventListener("DOMContentLoaded", ...) or defer scripts to ensure the DOM is ready.
  • Avoid excessive DOM manipulation in loops—batch updates where possible.
  • Use classList to add or remove classes cleanly.

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic