appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

The DOM and events

Lesson 3 of 310 minBeginner

Find elements, change them and react to clicks.

The browser turns your HTML into a tree of objects called the DOM (Document Object Model). JavaScript can read and change it.

<button id="go">Click me</button>
<p id="out"></p>

<script>
  const button = document.querySelector("#go");
  const out = document.querySelector("#out");
  button.addEventListener("click", () => {
    out.textContent = "Clicked at " + new Date().toLocaleTimeString();
  });
</script>
  • document.querySelector("css selector") finds the first match, querySelectorAll finds all.
  • element.textContent = "..." sets text safely.
  • element.classList.add("active") toggles styles through CSS classes.
  • addEventListener("click", fn) runs a function on an event.

CarefulDo not insert user input with innerHTML: it can run malicious scripts (XSS). Use textContent for text.

Fetching data

const res = await fetch("https://api.example.com/items");
if (!res.ok) throw new Error("HTTP " + res.status);
const items = await res.json();

fetch returns a promise: await waits for the result inside an async function or a module script. Check res.ok because fetch does not fail on 404 or 500 by itself.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. Which method finds the first element matching a CSS selector?
2. Why avoid innerHTML with user input?
3. Does fetch reject the promise on a 404 response?
4. What does await do?

Key terms