The DOM: Changing the Page
The DOM (Document Object Model) is the browser's live tree of the page. JavaScript reads and changes it.
Selecting elements
const title = document.querySelector("h1"); // first match
const cards = document.querySelectorAll(".card"); // all matches (NodeList)
const form = document.getElementById("signup");
cards.forEach(card => console.log(card.textContent));
querySelector accepts any CSS selector: "#id", ".class", "nav a[href^='/learn']".
Changing content and attributes
title.textContent = "Welcome back"; // plain text: safe
link.setAttribute("href", "/learn");
img.alt = "Team photo";
input.value = "";
button.disabled = true;
Classes and styles
menu.classList.add("open");
menu.classList.remove("open");
menu.classList.toggle("open");
menu.classList.contains("open");
Prefer toggling classes defined in CSS over setting inline styles; it keeps design in your stylesheet.
Creating elements
function addTask(text) {
const li = document.createElement("li");
li.textContent = text; // safe for any user text
li.className = "task";
document.querySelector("#tasks").append(li);
}
The XSS trap: innerHTML
// DANGEROUS with user input
list.innerHTML += `<li>${userComment}</li>`;
// a comment like <img src=x onerror="stealCookies()"> runs code
Cross-site scripting (XSS) happens when user-provided text is inserted as HTML. Use textContent, createElement and setAttribute for anything that came from a user, a URL or an API. Use innerHTML only with fixed strings you wrote yourself.
Data attributes
Store small bits of data in HTML for your scripts:
<button class="delete" data-id="42">Delete</button>
button.dataset.id; // "42"
Showing and hiding
panel.hidden = true; // uses the HTML hidden attribute
panel.hidden = false;
Make sure your CSS does not override [hidden], for example with a display: flex rule on the same element.
Exercise
Build a to-do list: an input, an "Add" button and a list. New items are created with createElement and textContent. Clicking an item toggles a done class that strikes it through.
Check yourself
- Why is
textContentsafer thaninnerHTML? - How do you read
data-id="42"from an element? - Why toggle classes rather than set inline styles?
Votre progression est enregistrée dans ce navigateur uniquement.
Envoyer pour relecture (10 points)