๐ŸŸจ JavaScript Basics

JavaScript DOM Manipulation: A Practical Guide with Examples

By The CodeCraft Teamยทยท9 min read
DOM tree diagram with HTML nodes connected

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.

Enjoyed this article?

Share it with a fellow developer or explore more tutorials in our blog.

More articles

Related articles