classList switches an element's classes: add, remove, toggle and contains. Instead of setting colors from JavaScript one property at a time, you write the look in CSS, under a class such as .running, and JavaScript only says which state the element is in. Design stays in CSS; behavior stays in JavaScript.
EXAMPLE · WEB PAGE
loading editor…
WHAT THIS DOES
classList.add gave the paragraph the live class, and the CSS rule for .live changed its color. The JavaScript never mentions a color: it only says which state the element is in, and contains() confirms it.
YOUR TURN · WEB PAGE
Your turn → Add a .busy class to the CSS with a different color. Then use classList.toggle("busy") twice in a row, printing classList.contains("busy") after each, and watch it switch on and off.
loading editor…
Syntax has to be exact. Every quote, bracket, brace and parenthesis needs its partner, and every HTML tag you open needs closing. One slip and the script won't run; the message under the page will say where.
textContent or innerHTML? textContent sets plain text, exactly as given. innerHTML reads what you give it as HTML, so it can add tags. Use innerHTML only for markup you wrote yourself, never for anything a visitor typed: whatever HTML they type would run on your page, which is how sites get broken into.
Data attributes carry information for your JavaScript right in the HTML. <button data-minutes="25"> is read in JavaScript as button.dataset.minutes, and like everything that comes out of HTML it arrives as text, so convert it with Number() before doing math.
Some attributes are properties you can set directly: button.disabled = true greys a button out so it can't be pressed.
EXAMPLE · WEB PAGE
loading editor…
WHAT THIS DOES
data-minutes stored a value in the HTML. dataset.minutes read it back as the text "25", Number() turned it into a number for the math, and disabled = true greyed the button out.
YOUR TURN · WEB PAGE
Your turn → Add two more buttons with data-minutes of 5 and 45. Change the script to read the 45 button instead, and show the result in hours and minutes, such as 0 hours 45 minutes.
loading editor…
Syntax has to be exact. Every quote, bracket, brace and parenthesis needs its partner, and every HTML tag you open needs closing. One slip and the script won't run; the message under the page will say where.
◈ Graded Build
Using JavaScript only, put the page into its running state: give #status the class running and remove its class paused, set its text to the button's data-label, and disable the button.
Checked by using your page: clicking, typing and waiting, then reading what changed. 3 visible and 1 hidden checks.
loading editor…
Mark this lesson complete
Signed in, your progress follows you to every device.