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

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 the button to turn DarkTheme, body changes the background color and the menu was to change too, but only change the menu border.

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

    
asked by anonymous 14.02.2018 / 19:33

1 answer

1

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

i <= liCat.length

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

    
14.02.2018 / 20:09