JavaScript DOM Manipulation
JavaScript DOM manipulation is how you change a web page with code. The DOM (Document Object Model) is a tree of objects the browser builds from your HTML. Every element is a node you can find, read, change, add or remove.
Selecting Elements
document.querySelector(selector) returns the first element matching a CSS selector, and querySelectorAll returns all matches as a NodeList you can loop over with for...of or forEach.
document.body.innerHTML = `
<h2 id="title">Shopping list</h2>
<ul><li>Milk</li><li>Eggs</li><li>Bread</li></ul>`;
const title = document.querySelector("#title");
const items = document.querySelectorAll("li");
console.log(title.textContent, "-", items.length, "items");Shopping list - 3 items
Changing Content and Styles
textContent sets plain text safely. Use classList to add, remove or toggle CSS classes, and the style property for inline styles.
const box = document.createElement("div");
box.textContent = "I am a box";
box.style.padding = "12px";
box.style.background = "#ffe08a";
box.style.borderRadius = "8px";
box.classList.add("note");
document.body.append(box);
console.log(box.className);note (and a yellow rounded box appears)
Creating and Removing Elements
Create elements with document.createElement, then insert them with append, prepend, before or after. element.remove() deletes an element.
const list = document.createElement("ul");
for (const lang of ["HTML", "CSS", "JavaScript"]) {
const li = document.createElement("li");
li.textContent = lang;
list.append(li);
}
document.body.append(list);
list.firstElementChild.remove();
console.log(list.children.length);2 (the list shows CSS and JavaScript)
Attributes and Data Attributes
getAttribute and setAttribute work with any attribute. Custom data-* attributes are available through the dataset object.
const link = document.createElement("a");
link.href = "https://naeemamin.cloud";
link.textContent = "Visit site";
link.setAttribute("target", "_blank");
link.dataset.track = "header-link";
document.body.append(link);
console.log(link.getAttribute("target"), link.dataset.track);_blank header-link
innerHTML vs textContent
innerHTML parses a string as HTML, which is handy for templates but dangerous with user input because it can run injected scripts (XSS). Prefer textContent for any text that came from users.
Frequently asked questions
What is the difference between querySelector and getElementById?
getElementById only finds by id and is slightly faster. querySelector accepts any CSS selector, which makes it more flexible.
Why does querySelector return null?
The element does not exist yet when the script runs, or the selector is wrong. Load scripts with defer or at the end of the body.
Should I use innerHTML or textContent?
Use textContent for text, especially user input. Use innerHTML only with trusted HTML.