-1

here's a part of the code where is function lightOn that must remove class 'light-on' when decorLight has it. Idk but its not working at all... There's similar function above that working.

document.addEventListener("DOMContentLoaded", function(event) {
document.documentElement.setAttribute("data-theme", "light");

const themeSwitcher = document.getElementById("theme-switcher");
const decorLight = document.getElementById("decorLight");

function transformSwitcher() {
    if (themeSwitcher.className == 'pressed')
        themeSwitcher.classList.remove('pressed');
    else themeSwitcher.classList.add('pressed');
}

function lightOn() {
    if (decorLight.className == 'light-on') 
        decorLight.classList.remove('light-on');
    else decorLight.classList.add('light-on');
}

themeSwitcher.onclick = function () {
    transformSwitcher();
    lightOn();
    let currentTheme = document.documentElement.getAttribute("data-theme");
    let switchToTheme = currentTheme === "dark" ? "light" : "dark";
    document.documentElement.setAttribute("data-theme", switchToTheme);
};
});
10
  • 2
    If the element has more than one class, decorLight.className will not equal light-on Commented Apr 1, 2021 at 19:43
  • 2
    Please post a minimal reproducible example. You can use a Stack Snippet to make it executable. Commented Apr 1, 2021 at 19:43
  • 2
    If you want to toggle a class (meaning put it on if it's not there, and remove it if it's there), JS has classList.toggle('light-on') for you. Commented Apr 1, 2021 at 19:44
  • I'm pretty sure the browser developers tested their code pretty well before releasing it, and that classList.remove works as intended. Note that there is also a classList.contains function... Commented Apr 1, 2021 at 19:45
  • @Barmar Maybe point out that OP in that case needs to do classList.contains('light-on'). Commented Apr 1, 2021 at 19:45

1 Answer 1

0

That is because you are checking the className. className can have multiple classes.

Just check your class with

if (themeSwitcher.classList.contains('pressed') and
if (decorLight.classList.contains('light-on')

you can also toggle the class with:

themeSwitcher.classList.toggle('pressed')

and save the if condition.

You can learn more about the classList API here:

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.