Here’s a beginner-to-intermediate guide to DOM Manipulation — one of the core skills in web development.
🧠 What is the DOM?
DOM (Document Object Model) is a tree-like structure that represents your web page in memory. Each element, attribute, and piece of text is a node that JavaScript can access and modify.
🔧 Why DOM Manipulation Matters
Using JavaScript, you can:
Change content (
text
,HTML
, etc.)Add/remove elements
Handle user interactions (click, keypress)
Dynamically update styles and layout
✅ Accessing Elements
<p id="demo">Hello</p>
📌 JavaScript Selectors
// By ID
const para = document.getElementById("demo");
// By class
const items = document.getElementsByClassName("item");
// By tag
const paragraphs = document.getElementsByTagName("p");
// Modern (recommended)
const first = document.querySelector("#demo"); // CSS-style selector
const all = document.querySelectorAll(".item"); // NodeList
📝 Changing Content
para.textContent = "Hi there!";
para.innerHTML = "<strong>Bold text</strong>";
textContent
is for plain text.innerHTML
can render HTML tags.
🎨 Changing Styles
para.style.color = "blue";
para.style.fontSize = "20px";
Use
.style.property
for inline CSS.
➕ Creating and Adding Elements
const newDiv = document.createElement("div");
newDiv.textContent = "I'm new!";
document.body.appendChild(newDiv); // Adds to end of <body>
➖ Removing Elements
const element = document.getElementById("remove-me");
element.remove();
Or older method:
element.parentNode.removeChild(element);
🔁 Loop Through Elements
const items = document.querySelectorAll(".item");
items.forEach((el) => {
el.style.background = "lightyellow";
});
🧩 Handling Events
const btn = document.querySelector("#clickMe");
btn.addEventListener("click", function () {
alert("Button clicked!");
});
You can respond to events like
click
,input
,keydown
,submit
, etc.
🎯 Example: Toggle Dark Mode
const btn = document.getElementById("toggleTheme");
btn.addEventListener("click", () => {
document.body.classList.toggle("dark");
});
In CSS:
.dark {
background: #222;
color: white;
}
🧪 Common DOM APIs
Task | Method |
---|---|
Create element | document.createElement() |
Append child | element.appendChild() |
Set attributes | element.setAttribute() |
Add event | element.addEventListener() |
Select element | querySelector() , getElementById() |
✅ Summary
Use
querySelector()
andquerySelectorAll()
for clean, modern selection.Modify content with
.textContent
or.innerHTML
.Add interactivity with
.addEventListener()
.DOM manipulation is the foundation of JS frameworks like React, Vue, etc.