JavaScript AcademyProfessional Engineering
Level 3 · Interactive Web ApplicationsModule 11: The Document Object ModelLesson 55 of 150About 40 minutes

Lesson 55: Updating styles, attributes and classes

01Opening question

A tab looks selected, a button looks disabled, a row is highlighted. How does JavaScript change how elements look and behave without rewriting the CSS?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

Classes carry the styling; attributes describe state for the browser and assistive technology.

const tab = document.querySelector("#tab-2");
tab.classList.add("active");
tab.setAttribute("aria-selected", "true");
console.log(tab.className, tab.getAttribute("aria-selected"));

03Objective and prerequisites

Learning objective: Add, remove and toggle classes, read and set attributes and data-* values, set inline styles sparingly, and keep ARIA attributes in sync with the visual state.

You need: Lesson 54: Creating and removing elements

Skills practised: The DOM, Attributes, classes and styles.

04Explanation

el.classList.add("active"), .remove(...), .toggle(...) and .contains(...) manage CSS classes. Let CSS decide what a class looks like.

el.getAttribute("href") and el.setAttribute("href", "/shop") read and write HTML attributes; removeAttribute deletes one.

data-* attributes store small values on elements: data-id="7" is read with el.dataset.id (always a string).

el.style.color = "red" sets an inline style. Use it for values computed in JavaScript (positions, sizes); prefer classes for everything else.

05Definitions

classList
An element's list of CSS classes with add, remove, toggle and contains.
Attribute
A name-value pair written on an HTML tag, such as href or alt.
dataset
Access to an element's data-* attributes as properties.
Boolean attribute
An attribute such as disabled or hidden that is on whenever it is present.
ARIA attribute
An aria-* attribute that communicates role and state to assistive technology.

Open the full glossary

06Visual learning object

DOM update visualizer. Toggle classes, attributes and styles on a live preview and see the element's markup change.

Loading the interactive object…

Open the full DOM update visualizer page with its guided experiment.

07Examples

ex-055-01Classes Browser page (sandboxed preview)

classList adds, removes, toggles and checks classes.

const fav = document.querySelector("#fav");
fav.classList.add("active");
console.log(fav.className);
fav.classList.toggle("active");
console.log(fav.classList.contains("active"), fav.className);
Sample input
None
Expected output
btn active false btn
Common mistake
Assigning className = "active" and losing the btn class.
Try this
Toggle twice and predict the result.
Source
examples/ex-055-01-classlist.js

ex-055-02Attributes Browser page (sandboxed preview)

getAttribute and setAttribute work with any attribute.

const link = document.querySelector("#link");
console.log(link.getAttribute("href"));
link.setAttribute("href", "/shop");
link.textContent = "Shop";
const logo = document.querySelector("#logo");
logo.setAttribute("alt", "Shop logo");
console.log(link.getAttribute("href"), logo.alt);
Sample input
None
Expected output
/home /shop Shop logo
Common mistake
Reading link.href and getting the full absolute URL instead of the attribute text.
Try this
Remove the alt attribute and log hasAttribute("alt").
Source
examples/ex-055-02-attributes.js

ex-055-03data-* attributes Browser page (sandboxed preview)

dataset reads data-* attributes as strings.

const tea = document.querySelector("#tea");
console.log(tea.dataset.id, typeof tea.dataset.id);
console.log(Number(tea.dataset.unitPrice) * 2);
tea.dataset.selected = "yes";
console.log(tea.getAttribute("data-selected"));
Sample input
None
Expected output
7 string 9 yes
Common mistake
Forgetting that dataset values are strings.
Try this
Add data-stock="0" and print Sold out when it is 0.
Source
examples/ex-055-03-dataset.js

ex-055-04Inline style and computed style Browser page (sandboxed preview)

style sets inline values; getComputedStyle reads the final result.

const msg = document.querySelector("#msg");
console.log(getComputedStyle(msg).display);
msg.classList.remove("hidden");
msg.style.color = "green";
console.log(getComputedStyle(msg).display, msg.style.color);
Sample input
None
Expected output
none block green
Common mistake
Reading el.style.display and getting an empty string because the value comes from a stylesheet.
Try this
Set msg.style.display = "none" and compare.
Source
examples/ex-055-04-computed.js

ex-055-05Keep ARIA in sync Browser page (sandboxed preview)

The same click updates the class, aria-expanded and hidden.

const btn = document.querySelector("#toggle");
const panel = document.querySelector("#faq");
function setOpen(open) {
  btn.setAttribute("aria-expanded", String(open));
  panel.hidden = !open;
  btn.textContent = open ? "Hide answer" : "Show answer";
}
setOpen(true);
console.log(btn.getAttribute("aria-expanded"), panel.hidden, btn.textContent);
Sample input
None
Expected output
true false Hide answer
Common mistake
Changing only the visual style so screen readers never hear the new state.
Try this
Call setOpen(false) and log the same values.
Source
examples/ex-055-05-aria.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Fix the class name

Pass class names without the dot.

const row = document.querySelector("#row");
row.classList.add(".highlight");
console.log(row.classList.contains("highlight"));

Flag expensive items

Read dataset values and set classes.

// TODO: add the class "expensive" to every li whose data-price is above 10

Tab switcher

Keep classes, ARIA and hidden panels in sync.

// Write setTab(index)

09Prediction

Commit to an answer first, then run the real code to compare.

// HTML: <button id="b">Save</button>
const b = document.querySelector("#b");
b.setAttribute("disabled", "false");
console.log(b.disabled);

What is printed?

10Debugging investigation

The Save button never re-enables

After the form becomes valid, the Save button should be enabled, but it stays greyed out.

const save = document.querySelector("#save");
function setValid(valid) {
  save.setAttribute("disabled", !valid);
}
setValid(true);
console.log("Disabled: " + save.disabled);

More cases in the Debugging Detective Laboratory

11Practical scenario

Visual state from classes

A design system defines .is-selected, .is-loading and .has-error in CSS. Scripts only add and remove these classes (plus the matching ARIA attributes), so designers can restyle states without touching JavaScript.

// button.classList.add("is-loading");
// button.setAttribute("aria-busy", "true");
console.log("Scripts switch classes; CSS decides the look");

12Knowledge check

1. With <p id="p" class="a">, what is printed?

const p = document.querySelector("#p");
p.classList.add("b");
console.log(p.className);
  • a b
  • b
  • a
  • .a .b

2. How do you read data-user-id="42"?

  • el.dataset.userId
  • el.dataset["user-id"]
  • el.data.userId
  • el.userId

3. Why is the button still disabled?

btn.setAttribute("disabled", false);
  • setAttribute("disabled", false) still sets the boolean attribute
  • The button is hidden
  • false must be a string
  • disabled cannot be changed

4. What is printed?

const d = document.createElement("div");
d.classList.toggle("x");
d.classList.toggle("x");
console.log(d.classList.contains("x"));
  • true
  • false
  • undefined
  • An error

5. Why update aria-expanded when a panel opens?

  • It changes the colour
  • Screen readers announce the new state
  • It is required for clicks to work
  • It makes the panel faster

6. To show an error state on a field, which is easier to maintain?

  • el.style.border = "2px solid red"; el.style.background = "#fee";
  • el.classList.add("has-error") with the styles in CSS
  • el.setAttribute("style", "...") with every property
  • Replace the element with a new red one

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Fix the class name: Prints true; Class is exactly highlight
  • Flag expensive items: Right items flagged; Uses dataset
  • Tab switcher: Prints the visible panel; ARIA in sync; Switch back to the first tab

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-03-interactive-web-applications/module-11-the-document-object-model/lesson-055-updating-styles-attributes-and-classes/. Every example on this page is generated from those files.

These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.

15Summary and next steps

  • classList manages classes; CSS decides the look.
  • getAttribute/setAttribute work with any attribute; dataset reads data-*.
  • Boolean attributes are on whenever present.
  • Keep ARIA state in sync with visual state.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation classes, attributes and styles
Context: I am learning classes, attributes and styles in JavaScript.
Task: Explain classList, attributes, dataset and inline styles, and when to use each.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction classes, attributes and styles drill
Context: I have practised classes, attributes and styles.
Task: Give me six snippets that change classes and attributes and ask what each prints.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging classes, attributes and styles bug
Context: My button stays disabled even though I set disabled to false.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation classes, attributes and styles practice
Context: I finished the classes, attributes and styles exercises.
Task: Create three exercises that switch visual state with classes and ARIA.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review classes, attributes and styles review
Context: Here is my code that uses classes, attributes and styles.
Task: Review my DOM code for inline styles that should be classes and missing ARIA updates.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.