Chapter 15

Changing the Page with the DOM

Use the DOM to find elements and change the page content, styles and attributes with JavaScript.

Changing the Page with the DOM

When a browser loads HTML it builds a live model of the page called the DOM, short for Document Object Model. JavaScript can read and change this model, and the page updates instantly. This is how content appears, hides or changes after the page has loaded.

Finding elements

The document object represents the whole page. The most flexible way to grab an element is querySelector, which takes a CSS selector and returns the first match. Use querySelectorAll to get every match as a list.

const title = document.querySelector('#heading');
const firstCard = document.querySelector('.card');
const allCards = document.querySelectorAll('.card');

You may also see getElementById, which finds one element by its id.

Changing content and attributes

Once you have an element you can change what it shows. textContent sets plain text, while innerHTML sets markup. Prefer textContent when you only need text, because inserting untrusted HTML can be unsafe.

title.textContent = 'Welcome back';

const link = document.querySelector('a');
link.setAttribute('href', 'https://example.com');

Changing styles and classes

You can set inline styles through the style property, but the cleaner way is to add or remove a CSS class with classList. Keeping the look in CSS and only toggling classes in JavaScript keeps code tidy.

const box = document.querySelector('.box');
box.classList.add('active');
box.classList.remove('hidden');
box.classList.toggle('open');

Reacting to input

Combine what you know: find an element, listen for an event, then change the DOM inside the handler.

const btn = document.querySelector('#count');
const out = document.querySelector('#out');
let clicks = 0;

btn.addEventListener('click', function () {
  clicks = clicks + 1;
  out.textContent = 'Clicks: ' + clicks;
});

Each click runs the handler, updates the variable and writes the new text into the page.

Reading form values

To read what a user typed, use the input element value property. Remember it is always text, so convert it with Number if you need to do maths.

Remember: querySelector uses CSS selectors, so a hash means an id and a dot means a class. Use textContent for plain text and toggle classList instead of writing lots of inline styles.

Stuck on this topic? A verified JomKelas tutor can walk you through it.

Find a verified tutor