🟨 JavaScript Basics

JavaScript DOM Manipulation: A Practical Guide with Examples

By Shubham Sharma··9 min read
DOM tree diagram with HTML nodes connected

Before I picked up React, everything I built — three years of PHP and Laravel dashboards, WordPress plugins, jQuery-heavy admin panels — ran on vanilla DOM manipulation. And honestly, for 80% of the work I still do today, plain document.querySelector and addEventListener are all I need. No React, no build step, no 200KB of framework. This guide is the exact mental model of the DOM I use when I open a fresh index.html on a client project: what the tree really is, how to read it, how to change it, and how to listen for user events without leaking memory.

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