Web Development · Module 6 · Lesson 11 min read

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

MethodReturns
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.id reads data-id="..." attributes.

Creating and removing elements

JavaScript
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

HTML
<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>