Loading…
Everything will be ready in few seconds
- Theory
- Theory
- Comments
First class
We found the elements, and then what? Now we need to visually change them somehow. Fortunately, we found that the layout designer thoughtfully created styles for different states of the products. In style.css
, you can find different CSS rules:
- class
product--available
is most likely needed for products in stock; - and
product--unavailable
is added, apparently, when the products are out of stock; - and the
product--special
class is more than likely responsible for special offers.
But why are we playing the guessing game? Let’s add classes and see what we get.
Since DOM-elements are objects, they all have a set of properties and methods. One of the properties of DOM elements is the classList
object. It contains methods for managing DOM element classes, including the add()
method. We can use it to specify which class you want to add to the element.
The syntax is simple. First, we specify the DOM element to which we want to add a class, then access the classList
property using dot and call the add()
method by transferring to it a string with the required class. Note that you don’t need to have a dot before the class name. As a result, adding a class looks like this:
// When searching for an element by class, use dot
var product = document.querySelector('.product');
// But when we add a class, there is no dot!
product.classList.add('product--sale');
The result of classList.add()
is the same as when we manually add a class to the layout:
<!-- Initial markup state -->
<li class="product">
…
</li>
<!-- State after calling classList.add -->
<li class="product product--sale">
…
</li>
Add to the found elements the class of the product that is not available and the special offer class.
- index.html
- style.css
- script.js
Thanks! We’ll fix everything at once!
Click inside the mini browser to put the focus in this window.
Comments