Command Palette

Search for a command to run...

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

dataset: your own data on elements

* turned the string into a number, but + joined two strings into 199.51. Setting dataset.discountCode created data-discount-code, and the CSS attribute selector turned the item green.

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?

dataset: your own data on elements

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

42 string
true
399 199.51
SAVE10
{ id: '42', price: '199.5', inStock: 'true', discountCode: 'SAVE10' }
false