Changing the page

Topic 2 of 5 in Working with the DOM6 min readBeginnerFree course

Overview

Once you’ve selected an element, you can change almost anything about it: its text, its classes, its attributes, its style. The page updates immediately.

The element <a class="card active" href="/c" data-topic-id="loops" hidden>Loops</a> with the property that changes each part: classList for class, el.href or setAttribute for attributes, el.dataset.topicId for data attributes, el.hidden for visibility, el.textContent for the text inside, and el.style for inline styles.

Text and HTML

JavaScript
const title = document.querySelector('h1');
title.textContent = 'Changing the page';

textContent treats whatever you give it as plain text. Even '<b>hi</b>' is shown literally, tags and all — which is exactly what makes it safe.

innerHTML lets you set HTML, but never use it with text that came from users — it can run injected scripts. Prefer textContent, or build elements (next topic).

JavaScript
const comment = '<img src=x onerror="stealCookies()">'; // from a user
box.innerHTML = comment;   // ✗ the browser runs the attacker's code
box.textContent = comment; // ✓ shown as harmless text

This attack is called cross-site scripting (XSS). innerHTML is fine for HTML you wrote, but anything from a form, URL or server must go through textContent.

To read text, textContent gives all the text inside an element, including hidden parts. innerText gives the text as displayed, respecting CSS — it’s slower, but sometimes what you want.

Classes

Keep your styles in CSS, and use JavaScript to switch classes on and off:

JavaScript
const menu = document.querySelector('.menu');
menu.classList.add('open');
menu.classList.remove('open');
menu.classList.toggle('open');
menu.classList.contains('open'); // true or false

toggle returns the new state, and takes an optional second argument to force it: menu.classList.toggle('open', isWide).

This keeps the jobs separate: CSS decides how an “open” menu looks; JavaScript only decides when it’s open.

CSS
.menu { display: none; }
.menu.open { display: block; }

Attributes

JavaScript
const link = document.querySelector('a');
link.href = '/courses/';
link.setAttribute('aria-current', 'page');
link.removeAttribute('target');
link.getAttribute('href'); // '/courses/' — exactly as written
link.hasAttribute('target'); // false

const card = document.querySelector('.card');
card.dataset.topicId = 'arrow-functions'; // sets data-topic-id

Most standard attributes are also properties of the element: img.src, input.value, a.href, button.disabled, input.checked. Properties are usually easier, and they give you useful types — button.disabled is a boolean, not a string.

A subtle difference: link.href gives the full resolved URL (https://site.com/courses/), while getAttribute('href') gives what’s written in the HTML.

data attributes

data-* attributes are the standard way to attach your own information to elements. The dataset object converts names between dashed HTML and camelCase JavaScript:

HTML
<button data-topic-id="loops" data-minutes="6">Start</button>
JavaScript
button.dataset.topicId;  // 'loops'
button.dataset.minutes;  // '6' — always a string
Number(button.dataset.minutes); // 6

Styles

You can set inline styles directly, which is useful for values calculated in code:

JavaScript
const bar = document.querySelector('.progress span');
bar.style.width = `${percent}%`;
bar.style.backgroundColor = 'green'; // CSS names in camelCase
bar.style.setProperty('--progress', percent); // CSS custom properties

To read the style actually applied (from all your CSS, not just inline styles), use getComputedStyle:

JavaScript
getComputedStyle(bar).width; // e.g. '240px'

Setting CSS custom properties from JavaScript is a neat technique: CSS does all the styling, and JS only feeds in a number.

Show and hide with the hidden attribute: panel.hidden = true. It’s simple and screen readers understand it.

Forms and inputs

Form elements have their own properties for their current state:

JavaScript
input.value = 'Asha';          // text in a text box
checkbox.checked = true;       // tick a checkbox
select.value = 'beginner';     // choose an option
button.disabled = true;        // grey out a button
input.focus();                 // put the cursor in it

More on these in Forms.

Changing many elements

querySelectorAll returns a list, so loop over it:

JavaScript
document.querySelectorAll('.card').forEach((card) => {
  card.classList.remove('active');
});

A common pattern is “make only this one active”:

JavaScript
function selectTab(tab) {
  document.querySelectorAll('.tab').forEach((t) => t.classList.toggle('active', t === tab));
}

Accessibility

When JavaScript changes the page, make sure people using screen readers get the same information. Keep ARIA attributes in sync with what’s on screen — aria-expanded on a menu button, aria-pressed on a toggle, aria-current="page" on the current link — as in this topic’s exercise.

Exercise

Toggle a highlight

When the button is clicked, toggle the class highlight on the element with id note, and set the button’s aria-pressed attribute to match ('true' or 'false').

JavaScript
const button = document.querySelector('button');
const note = document.querySelector('#note');

Summary

  • Use textContent to set text safely; avoid innerHTML with user data.
  • classList.add, remove and toggle switch styles defined in CSS.
  • Common attributes are properties (el.href); others use setAttribute.
  • dataset reads and writes data-* attributes.
  • Use el.style for calculated values and the hidden property to show and hide.