JavaScriptLesson 9 of 10Jump to practice
The DOM
Find elements on the page and change their text, styles and classes from JavaScript.
When the browser loads your HTML, it builds a tree of objects, one for every element. That tree is the DOM (Document Object Model). JavaScript changes the page by changing the DOM.
Finding elements
document.querySelector() takes any CSS selector and gives you the first match.
document.querySelector("h1"); // first <h1>
document.querySelector(".price"); // first element with class="price"
document.querySelector("#menu"); // the element with id="menu"
document.querySelectorAll("li"); // every <li>
You already know these selectors from the CSS course.
Changing text and style
<h1 id="title">Good morning</h1>
<p class="note">This text will change.</p>
<script>
const title = document.querySelector("#title");
title.textContent = "Good evening";
title.style.color = "teal";
const note = document.querySelector(".note");
note.textContent = "JavaScript changed this paragraph.";
note.style.fontStyle = "italic";
</script>In JavaScript, CSS properties with a dash become camelCase: font-style becomes style.fontStyle, background-color becomes style.backgroundColor.
Classes are better than styles
Setting lots of style properties in JavaScript gets messy. A cleaner pattern: put the styles in CSS under a class, and use JavaScript only to add or remove the class.
| Method | Does |
|---|---|
classList.add("x") |
Adds the class |
classList.remove("x") |
Removes it |
classList.toggle("x") |
Adds it if missing, removes it if present |
classList.contains("x") |
Gives true or false |
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; padding: 12px; transition: background 0.3s; }
body.dark { background: #1a2330; color: #e4f0ee; }
</style>
</head>
<body>
<h2>Dark mode</h2>
<p>Press the button to switch.</p>
<button onclick="document.body.classList.toggle('dark')">Toggle dark mode</button>
</body>
</html>Creating elements
document.createElement("li")makes a new element.- Set its
textContent, classes and attributes. parent.append(child)puts it on the page.
<ul id="list">
<li>First item</li>
</ul>
<button id="add">Add an item</button>
<script>
const list = document.querySelector("#list");
let count = 1;
document.querySelector("#add").addEventListener("click", () => {
count++;
const item = document.createElement("li");
item.textContent = "Item number " + count;
list.append(item);
});
</script>To remove an element, call element.remove().
Practice
Check what you just learned. Fill in the missing code, then answer the quiz.
Exercise 1Solved
Find the first element with the class
title.const el = document.(".title");It takes a CSS selector.
Exercise 2Solved
Add the class
activeto the element.el.classList.("active");Exercise 3Solved
Create a new paragraph element.
const p = document.("p");
Finish the practice to complete this lesson.
Sign in to keep your progress on any device.
