Skip to curriculum
Jump to the editor

17.2. Add, remove and toggle classes

Easy
Topics
15–25 min

Almost every interactive widget switches classes: a menu gets open, a tab gets selected, a field gets invalid. element.classList does this for you, and knowing what it does underneath (how it reads the attribute, why it never adds a class twice, when it throws) is a common interview task and the quickest way to understand it.

Write four helpers in classes.js that work on the class attribute itself, without classList.

Signature

JAVASCRIPT
hasClass(element, name)             // returns true or false
addClass(element, ...names)         // returns nothing
removeClass(element, ...names)      // returns nothing
toggleClass(element, name, force)   // returns true or false

Requirements

  1. The names of an element are its class attribute split on any run of ASCII whitespace (space, tab, line feed, form feed, carriage return). A missing attribute means no names.
  2. hasClass matches whole names exactly (case-sensitive). It never throws: for "" or a name containing a space it returns false.
  3. addClass adds each name that is not there yet, at the end, in the order given.
  4. removeClass removes every copy of each name given and keeps the others in order. A name that is not there is skipped.
  5. When the helpers write, the attribute is the names joined by single spaces with repeats removed (the first copy stays), as classList writes it.
  6. When the element had no class attribute and no names are left to write, no attribute is created. When it had one, it is written even if it is now empty (class="").
  7. toggleClass removes the name if present and adds it if missing, and returns whether the element has it afterwards. With force true it only adds; with force false it only removes.
  8. In addClass, removeClass and toggleClass, an empty name throws a DOMException named "SyntaxError", and a name containing whitespace throws one named "InvalidCharacterError". Every name is checked before anything changes.
  9. The helpers work on SVG elements as well as HTML elements.

Examples

JAVASCRIPT
// <button class="btn  btn-primary btn">
hasClass(button, "btn");          // true
hasClass(button, "primary");      // false: only part of a name

addClass(button, "wide", "btn");  // class="btn btn-primary wide"
removeClass(button, "btn");       // class="btn-primary wide"
JAVASCRIPT
toggleClass(menu, "open");        // true: added
toggleClass(menu, "open");        // false: removed
toggleClass(menu, "open", false); // false: stays removed
JAVASCRIPT
addClass(tab, "ok", "two words"); // throws InvalidCharacterError; "ok" is not added
removeClass(document.createElement("p"), "x"); // still no class attribute

Environment

  • Plain JavaScript in a browser page; the tests call the four global functions on elements they create.
  • element.classList is not allowed: on the tests' elements it throws. Use getAttribute("class") and setAttribute("class", …).
  • element.className is a string only on HTML elements; on SVG elements it is an object.

Hints

  1. If one helper turns the attribute into a clean list of names and another writes a list back, what is left for the four functions?
  2. When should a write be skipped entirely?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…