Start learning free

LESSON 31 OF 161 · FRONTEND: JAVASCRIPT IN THE BROWSER

Change Classes in JavaScript

Practice

Every element has a class attribute, and the stylesheet decides what each class does. So the simplest way for a script to change what shows is to change an element's classes, and let the CSS do the rest.

element.classList is the list of the element's classes. add("x") puts a class in and keeps the others, remove("x") takes one out, toggle("x") removes it when it is there and adds it when it is not, and contains("x") answers true or false. element.className is the whole attribute as one string.

// in the HTML: <nav id="menu" class="menu">
const menu = document.querySelector("#menu");
menu.classList.add("open");
console.log(menu.className);                    // menu open
console.log(menu.classList.contains("open"));   // true
menu.classList.toggle("open");                  // removes it again

In styles.css, a card with the class sold-out shows its Sold out badge and hides its Buy button, and .hidden means display: none. The notebook is out of stock, and the side note <aside id="note" class="hidden"> should appear. When the check opens the page, it must print:

> open the page
  …
  console.log: The lamp card has data-id 3
  console.log: Notebook classes: card sold-out
  console.log: The note is hidden: true
  screen:
    …
        item
          heading 3: Notebook
          image: A notebook with a green cover
          text: $7
          text: Sold out
          link: Details -> /products/2
    …
      aside
        text: Free delivery on orders over $30

Your task: at the end of app.js, find the notebook's card, add the class sold-out to it and log "Notebook classes:" with its className. Then find the side note, log "The note is hidden:" with whether it has the class hidden, and toggle that class.


Assignment
Follow the Coding Tutorial to mark the notebook as sold out with classList.add and to show the side note with classList.toggle.


Hint
Class names go without the dot: "sold-out", not ".sold-out". Log whether the note is hidden before you toggle it, or the log will say false.


STEP 1 OF 6
    Ctrl + Enter to check

    Dom Classes in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free