Selecting & Changing Elements
The DOM
The browser turns HTML into a tree of objects, the DOM, which JavaScript can read and change. Changes appear on screen immediately.
Selecting elements
| Method | Returns |
|---|---|
document.querySelector(".card") | the first match (any CSS selector) |
document.querySelectorAll("li") | all matches (a NodeList; loop with forEach) |
document.getElementById("title") | the element with that id |
Changing content
el.textContent = "Hi"sets plain text. ✅ Safe.el.innerHTML = "<b>Hi</b>"parses HTML. ⚠️ Never use it with user input, because it allows XSS attacks.
Changing styles and classes
el.classList.add("active"),.remove(),.toggle(),.contains(). Prefer switching classes over setting inline styles.el.style.color = "red"for one-off changes.el.dataset.idreadsdata-id="..."attributes.
Creating and removing elements
const li = document.createElement("li");
li.textContent = "New item";
list.append(li); // add at the end
li.remove(); // delete
💡 Scripts that touch the DOM should use <script defer> (or sit at the end of <body>) so the elements exist before the code runs.
Example
<h1 id="title">Shopping list</h1>
<ul id="list"></ul>
<button id="add">Add item</button>
<style>
.done { text-decoration: line-through; color: gray; }
</style>
<script>
const list = document.querySelector("#list");
const items = ["Milk", "Bread"];
function addItem(text) {
const li = document.createElement("li");
li.textContent = text; // safe: no HTML parsing
li.addEventListener("click", () => li.classList.toggle("done"));
list.append(li);
}
items.forEach(addItem);
document.querySelector("#add").addEventListener("click", () =>
addItem("Item " + (list.children.length + 1)));
document.getElementById("title").style.color = "#4f46e5";
</script>