Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 8.4 — Attributes, Classes and Data
JavaScript · Example 2 of 3

classList: add, remove, toggle, replace

toggle returns whether the class is present afterwards. toggle("primary", true) left it on because the second argument forces the result. The button is red now because .danger replaced .primary.

Attributes are what the HTML says (getAttribute, setAttribute); properties are the live values on the DOM object (input.value); classList adds, removes and toggles classes, and dataset reads and writes your own data-* values.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

A <button data-count="0"> shows a number. Write bump(button) that adds 1 to its data-count, updates the button's text to the new count, and returns the new number.

02

Write setSelected(row, isSelected) that adds or removes the class selected and sets aria-selected to "true" or "false". Test it on one row.

Explain it without notes

01

What is the difference between an attribute and a property? Give an example where they differ.

02

How do boolean attributes work, and how do you turn one off from JavaScript?

03

Why prefer classList over className? What does toggle return?

04

What are data-* attributes and how does dataset name them?

classList: add, remove, toggle, replace

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

btn primary large
false
true
false
true
btn danger
<button#btn.btn.danger>