The DOM: changing the page with JavaScript

This is where HTML, CSS and JavaScript finally meet. When the browser loads your HTML, it builds a tree of objects in memory, one object per element. That tree is the DOM (Document Object Model), and JavaScript can read and change it. Change the DOM and the page on screen changes instantly.

Step one is finding an element. document.querySelector() takes a CSS selector, the same kind you wrote in the CSS lessons, and returns the first element that matches:

const title = document.querySelector("h1");
const intro = document.querySelector(".intro");
const box = document.querySelector("#score");

A dot means a class, a # means an id. If nothing matches you get null, and trying to use null gives an error like "Cannot read properties of null". When you see that, your selector is probably wrong. document.querySelectorAll() returns every match, as a list you can loop over or index like an array.

Step two is changing it. textContent is the text inside an element, and you can set it:

title.textContent = "Welcome back!";

For styling, do not set colours one by one from JavaScript. Write a CSS class, then switch it on and off with classList:

box.classList.add("active");
box.classList.remove("active");
box.classList.toggle("active");

That keeps the look in CSS and the logic in JavaScript, and each one stays easy to change.

One gotcha: put your <script> after the elements it uses (or at the end of the page). The browser reads top to bottom, and a script cannot find an element that has not been built yet.

Try it yourself

Edit it. Break it. Run it again.
<style>
  .done {
    text-decoration: line-through;
    color: gray;
  }
</style>
<h1>Loading...</h1>
<ul>
  <li>Homework</li>
  <li>Laundry</li>
  <li>Practise guitar</li>
</ul>
<script>
  const title = document.querySelector("h1");
  title.textContent = "My to-do list";

  const tasks = document.querySelectorAll("li");
  tasks[1].classList.add("done");
  console.log("There are", tasks.length, "tasks");
</script>
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

Your turn

Type it yourself. That is the whole trick.

1Change the heading

Using JavaScript in the <script> tag (leave the HTML line alone), change the text of the heading with id title to Hello, DOM!

<h1 id="title">Loading...</h1>
<script>
  // find the heading and change its text
</script>
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

2Cross it off

Use classList to add the class done to the second list item only.

<style>
  .done {
    text-decoration: line-through;
  }
</style>
<ul>
  <li>Wake up</li>
  <li>Eat breakfast</li>
  <li>Learn the DOM</li>
</ul>
<script>
  const items = document.querySelectorAll("li");
</script>
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.