Skip to main content
Web MobileBeginner12 min readUpdated March 2025

The DOM & Browser APIs

Learn how JavaScript reads and changes web pages: selecting elements, handling events, storing data locally and building a small interactive component.

What Is the DOM?

The Document Object Model is the browser's tree representation of your HTML. JavaScript can read, add, change and remove nodes in that tree, which is how pages become interactive.

Selecting and Updating Elements

`querySelector` finds the first match for any CSS selector. Prefer `textContent` over `innerHTML` when inserting user-supplied text to avoid cross-site scripting (XSS).

javascript
const title = document.querySelector("#title");
title.textContent = "Hello, DOM!";

const items = document.querySelectorAll(".item");
items.forEach((el) => el.classList.add("highlight"));

const li = document.createElement("li");
li.textContent = "New task";
document.querySelector("#list").append(li);

Events and Event Delegation

Instead of attaching a listener to every list item, attach one to the parent and inspect `event.target`. This is faster and works for items added later:

javascript
const list = document.querySelector("#list");

list.addEventListener("click", (event) => {
  const item = event.target.closest("li");
  if (!item) return;
  item.classList.toggle("done");
});

document.querySelector("#form").addEventListener("submit", (event) => {
  event.preventDefault();
  const data = new FormData(event.target);
  console.log(Object.fromEntries(data));
});

Persisting Data with localStorage

`localStorage` stores strings in the browser across visits. Serialize objects with JSON and always guard against missing or invalid data:

javascript
function loadTodos() {
  try {
    return JSON.parse(localStorage.getItem("todos")) ?? [];
  } catch {
    return [];
  }
}

function saveTodos(todos) {
  localStorage.setItem("todos", JSON.stringify(todos));
}

const todos = loadTodos();
todos.push({ id: Date.now(), text: "Learn the DOM", done: false });
saveTodos(todos);

Key Takeaways

  • The DOM is a tree that JavaScript can read and modify.
  • Use textContent for plain text to avoid XSS.
  • Event delegation handles many elements with a single listener.
  • localStorage persists small amounts of string data; parse it defensively.

Contact Us

Have a question or feedback? Fill out the form below or reach us directly at support@nvaitraining.com