background-color does not work when it is used in "classList.toggle()"

Asked

Viewed 104 times

1

I have the following codes:

HTML:

<div class="barraLateral" id="barraLateral">
    <ul class="menuVertical" id="menuVertical">             
        <li name="liCat" onclick="darkTheme()"><i class="mdi mdi-theme-light-dark mdi-24px"></i><a name="cat">Dark Theme</a></li>
        <li name="liCat" onclick="deslogar()"><i class="mdi mdi-close-circle-outline mdi-24px"></i><a name="cat">Logout</a></li>
    </ul>
</div>

Javascript:

function darkTheme() {
    document.getElementById("corpoPagina").classList.toggle('bodyDark');
    var liCat = document.getElementsByName("liCat");
    for (var i = 0; i <= liCat.length; i++) 
    {
        liCat[i].classList.toggle('menuDark');
    }
}

CSS:

.menuDark {
    background-color: red;
    border: 1px solid red;
}

When the user clicks on the button to flip Darktheme, the body changes the background color and the menu was to change too, but only changes the menu border.

In other words: When executing the darkTheme function, the attribute border: 1px solid red the attribute is already executed background-color: red is not executed.

  • What are you using this loop for for?

  • include html in your question.

  • The for is used to place new class on all items in the <li>, goes along and adds. These <li> can increase the amount as the user enters new categories, so the for.

1 answer

1


The problem is in for, when the correct would be to use i < liCat.length and not:

i <= liCat.length

When traversing array, only the operator is used less than <, otherwise the variable i will have value greater than the number of items in the array returning error.

  • I made this change and unfortunately it still didn’t work. The new class is added, but only the attribute border which is applied to the elements. =(

  • Put in front of the background !important and take a test, like this: background-color: red !important;

  • It worked perfectly. Thank you very much dvd, you are beast!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.