The DOM: Querying and Modifying Elements
11 min read
The Document Object Model
The DOM is the browser's live, tree-structured representation of an HTML page. JavaScript can read and modify the DOM to update the page without a reload.
Selecting Elements
javascript
// Single element
const title = document.querySelector("h1");
const btn = document.querySelector("#submit-btn");
const card = document.querySelector(".card");
// Multiple elements → NodeList
const items = document.querySelectorAll(".list-item");
items.forEach(item => console.log(item.textContent));
// Legacy (still useful)
document.getElementById("main");
document.getElementsByClassName("card"); // HTMLCollectionReading and Changing Content
javascript
const el = document.querySelector("#output");
// Reading
el.textContent; // text only (safe)
el.innerHTML; // includes HTML tags (XSS risk!)
// Writing
el.textContent = "Updated text"; // safe
el.innerHTML = "<strong>Bold</strong>"; // only with trusted contentChanging Classes and Styles
javascript
el.classList.add("active");
el.classList.remove("hidden");
el.classList.toggle("open");
el.classList.contains("active"); // boolean
el.classList.replace("old", "new");
// Inline styles (avoid where possible — prefer classes)
el.style.color = "red";
el.style.display = "none";
// Reading computed styles
getComputedStyle(el).fontSize;Creating and Inserting Elements
javascript
const li = document.createElement("li");
li.textContent = "New item";
li.classList.add("list-item");
const ul = document.querySelector("ul");
ul.appendChild(li); // add at end
ul.prepend(li); // add at start
ul.insertBefore(li, ul.children[2]); // before index 2
// Modern: insertAdjacentHTML
ul.insertAdjacentHTML("beforeend", "<li>Fast item</li>");Ready to test yourself?
Practice JavaScript— quiz & coding exercises