Loading…
Everything will be ready in few seconds
- Theory
- Theory
- Comments
Let’s remove the class using classList.remove
We made sure that JavaScript really found an element with the page
class. Now it’s time to figure out how to switch themes. The selected element has a second class (light-theme
). When we activate it, the page is given a bright theme. We need to remove this class from the element when we switch themes in order to avoid mixing styles. To do this, we need the classList.remove
method. It is used as follows:
element.classList.remove('class');
This method removes the class that is indicated in parentheses from the element. Please note that we do not write a period in front of the class name in classList.remove
. This is not a selector, since JavaScript already knows that we are dealing with a class.
To disable the light theme by removing the light-theme
class from the page
element, let’s use the following instruction:
document.querySelector('.page').classList.remove('light-theme');
The resulting command is quite lengthy: you need to find the element, and then remove the class from it. Let’s see what happens when this instruction is executed:
<!-- Source markup -->
<body class="page light-theme">
…
</body>
<!-- Browser markup after classList.remove('light-theme') -->
<body class="page">
…
</body>
Let’s turn off the light theme using JavaScript!
- 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