Skip to content
Topic 2 of 5
Theory

Classes, Styles and Attributes

Appearance is changed through classes

To make an element red, big or hidden, the most convenient way is not to write styles in JavaScript, but to describe them in CSS under a class in advance and only turn that class on or off from code. This way styles stay in CSS, and JS is only responsible for the logic: "there's an error now — add the class error".

classList

Every element has classList — the set of its classes with handy methods:

const btn = document.querySelector("#buy");

btn.classList.add("active");          // add
btn.classList.remove("disabled");     // remove
btn.classList.toggle("open");         // not there — add, there — remove
btn.classList.contains("active");     // true / false — is the class there
btn.classList.add("big", "primary");  // several at once

toggle returns true if after the call the class is there, and false if it was removed. toggle has a second argument — a condition: el.classList.toggle("error", age < 18) adds the class when the condition is true and removes it when it's false. This saves you from if/else with add and remove.

There is also the className property — all classes as one string. Writing into it replaces all classes at once, so for a single class classList is better.

Styles directly: style

Sometimes the value isn't known in advance — the width of a progress bar, coordinates, a color from settings. Then you write into style right from code:

const bar = document.querySelector("#progress");
bar.style.width = "40%";
bar.style.backgroundColor = "tomato";   // background-color → backgroundColor
bar.style.marginTop = "8px";
bar.style.width = "";                   // remove your own style, go back to CSS

There are two rules:

  • CSS properties with a hyphen are written in camelCase: font-size → fontSize, z-index → zIndex.
  • The value is a string with units: "40%", "120px". The number 40 without units won't work for width.

el.style shows only the styles written into the style attribute (from JS or in HTML). The final style including CSS files can be found with getComputedStyle(el).width.

Hiding and showing

Three popular ways:

el.hidden = true;                 // the hidden attribute — the element is hidden
el.hidden = false;
el.style.display = "none";        // hide with a style
el.style.display = "";            // go back to what CSS says
el.classList.add("hidden");       // a class that has display: none in CSS

The class approach is the most flexible: in CSS you can make a smooth fade-out, and in JS there's still just one line.

Attributes

Any attribute from HTML can be read and changed:

const link = document.querySelector("a");
console.log(link.getAttribute("href"));     // "/catalog"
link.setAttribute("href", "/sale");
link.setAttribute("target", "_blank");
link.removeAttribute("target");
console.log(link.hasAttribute("target"));   // false

Common attributes have ready-made properties: img.src, a.href, input.disabled, input.checked, el.id. Boolean attributes (disabled, checked, hidden) are easier to change with a property: btn.disabled = true.

Your own data: data attributes

To store your own data in HTML (a product id, price, category), you use attributes that start with data-. In JavaScript they are available through dataset:

<li class="product" data-id="42" data-price="1990" data-in-stock="yes">Headphones</li>
const item = document.querySelector(".product");
console.log(item.dataset.id);        // "42"
console.log(item.dataset.price);     // "1990" — a string!
console.log(item.dataset.inStock);   // "yes" — data-in-stock → inStock
item.dataset.price = "1490";         // the attribute in HTML changes too

Hyphens in the name turn into camelCase, and the values are always strings (Number(...) for numbers).

Summary

  • Appearance — through classes: classList.add / remove / toggle / contains.
  • toggle(class, condition) — turn a class on only when the condition is true.
  • style.property = "value with units" — for values calculated in code.
  • Attributes: getAttribute, setAttribute, removeAttribute; your own data — data-* and dataset.

Dark Theme

Easy+10 XP

Write a function toggleTheme() that turns the dark class on <body> on and off: if the class isn't there — it adds it, if it is — it removes it. The function returns true if after the call the theme is dark, and false if it's light.

toggleTheme()  → true   (body.dark)
toggleTheme()  → false  (class removed)

Connect the connector to solve tasks

Task code runs on your own computer — faster and more reliable than in the browser. This needs the free CodeWithMe connector app. You only connect it once.

Looking for the connector on this computer…

  1. 1
    Download the connector for your system (Windows, macOS or Linux).Download the connectorOn the download page pick the file with your system in its name, e.g. windows-amd64.
  2. 2Run it and choose a folder for your solutions. It will install Python and Node.js there by itself when needed.
  3. 3
    Enter below the 6-digit code shown in the connector window (“Code for CodeWithMe”). If the browser asks about local network access — allow it.

The connector is open source (on GitHub), works only on your computer and runs code only after you enter the pairing code.