Selecting and updating elements
โ Report an issue with this lessonconst heading = document.querySelector("h1");
const cards = document.querySelectorAll(".card");
heading.textContent = "Updated!";
heading.style.color = "navy";
heading.classList.add("highlight");
querySelector returns the first match using a CSS-style
selector; querySelectorAll returns all matches as a
NodeList you can loop over with forEach:
cards.forEach(card => card.classList.add("visible"));
Create new elements and add them to the page:
const li = document.createElement("li");
li.textContent = "New item";
document.querySelector("ul").appendChild(li);
Try it yourself
Exercise: This sandbox can't render a real DOM, but you can practice the logic behind it. Given the cards array below, use forEach to build an array of strings in the same format you'd set as textContent for each new <li> ("Card: <title>"), then log them joined with ', '.
Expected output:
Card: Alpha, Card: Beta, Card: Gamma
Run your code and get it working before marking this lesson complete.
// free preview
8 more lessons โ including Project: build a live search box โ plus a certificate are waiting.
Unlock the full course โ $59.99