JavaScript DOM Manipulation: A Practical Guide with Examples

The Document Object Model (DOM) is the live tree of nodes that represents your HTML page. JavaScript can read it, change it, and react to user events โ all without a single library.
Selecting elements
const btn = document.querySelector("#save");
const items = document.querySelectorAll(".item");Changing content and attributes
btn.textContent = "Saved!";
btn.classList.add("is-success");
btn.setAttribute("disabled", "");Creating and inserting elements
const li = document.createElement("li");
li.textContent = "New item";
document.querySelector("ul").append(li);Listening to events
btn.addEventListener("click", () => {
console.log("clicked");
});Performance tip: batch DOM writes
Every DOM write can trigger layout. When updating many nodes, use a DocumentFragment or build an HTML string and inject once.
Frequently asked questions
Should I use innerHTML?
It's fast but dangerous with user input โ it can introduce XSS. Use textContent or createElement for user data.
External references
Enjoyed this article?
Share it with a fellow developer or explore more tutorials in our blog.
More articles