JavaScript DOM Manipulation
The DOM (Document Object Model) represents HTML as a JavaScript object tree. JavaScript can read, create, and modify HTML elements.
Selecting Elements
// By ID
let element = document.getElementById("myId");
// By CSS selector (first match)
let button = document.querySelector(".btn");
// All matching elements
let items = document.querySelectorAll(".item");
Remember: querySelector returns the first match, querySelectorAll returns all matches.
Changing Content
let el = document.getElementById("demo");
el.textContent = "New text"; // Plain text
el.innerHTML = "<strong>Bold</strong>"; // HTML content
Tip: Use textContent over innerHTML — it’s safer against XSS attacks.
Changing Styles
let box = document.getElementById("box");
box.style.backgroundColor = "red";
box.style.fontSize = "20px";
// Multiple styles at once
box.style.cssText = "background: blue; color: white;";
Remember: Style properties use camelCase (backgroundColor, not background-color).
Creating Elements
let div = document.createElement("div");
div.textContent = "Hello World";
div.className = "container";
document.body.appendChild(div);
Manipulating Classes
let box = document.getElementById("box");
box.classList.add("active");
box.classList.remove("inactive");
box.classList.toggle("visible");
box.classList.contains("active"); // true/false
Complete Example: Todo List
let input = document.getElementById("todo-input");
let btn = document.getElementById("add-btn");
let list = document.getElementById("todo-list");
btn.addEventListener("click", () => {
let text = input.value.trim();
if (!text) return;
let li = document.createElement("li");
li.textContent = text;
list.appendChild(li);
input.value = "";
});
Best Practices
- Cache selectors — Don’t query the DOM repeatedly
- Use textContent — Safer than innerHTML
- Use CSS classes for styling — Prefer
classListover directstylemanipulation - Batch DOM changes — Minimize reflows
- Check if element exists — Prevent null errors
Common Mistakes
- Querying too much — Cache your selectors
- Using innerHTML with user data — Security risk (XSS)
- Forgetting to append — Element won’t appear without
appendChild - Using camelCase for style properties —
fontSize, notfont-size - Not trimming input — Check for empty values