Patrick Dinty
Patrick Dinty

Reputation: 89

Adding class with jQuery only works for the first element

I am trying to code Darkmode on my website using jQuery and using classList.toggle to change colors. Everything is working fine for the most part, but navigation only works for the first li and a. Here is my code:

HTML

<div class="fixed-darkmode">
    <div class="darkmode-definition">
        <button class="nightModeButton">darkmode</button>
    </div>


    <nav style="padding-left: 100px;">
        <ul>
            <li><a href="#">Bio</a></li>
            <li><a href="#">Galéria</a></li>
        </ul>
    </nav>

CSS

li a {
    display: inline-block;
    font-family: 'Merriweather', serif;
    font-weight: 500;
    font-size: 22px;
    text-decoration: none;
    color: #171717;
    padding: 0 30px;
}

li a:hover {
    color: #171717;
    text-decoration: none;
}

body.night-mode {
    background: #181b23;
}

li a.night-mode {
    color: #fff !important;
}

Javascript (jQuery)

var nightModeToggleButton = document.querySelector(".nightModeButton");
var body = document.querySelector("body");
var navigacka = document.querySelector("a");

nightModeToggleButton.onclick = function() {
    nightModeToggleButton.classList.toggle("night-mode");
    body.classList.toggle("night-mode");
    navigacka.classList.toggle("night-mode");
};

Upvotes: 1

Views: 52

Answers (1)

Avanthika
Avanthika

Reputation: 4182

Changing

li a.night-mode {
    color: #fff !important;
}

to

.night-mode li a {
  color: #fff !important;
}

gives the result you are expecting.

Just a thought: Instead of applying color modifications directly on li or ul or a, have a class called light-mode maybe, and nest the styles associated to light-mode inside.

var nightModeToggleButton = document.querySelector(".nightModeButton");
        var body = document.querySelector("body");
        var navigacka = document.querySelector("a");


        nightModeToggleButton.onclick = function() {
            nightModeToggleButton.classList.toggle("night-mode");
            body.classList.toggle("night-mode");
            navigacka.classList.toggle("night-mode");
        };
li a {
    display: inline-block;
    font-family: 'Merriweather', serif;
    font-weight: 500;
    font-size: 22px;
    text-decoration: none;
    color: #171717;
    padding: 0 30px;
}

li a:hover {
    color: #171717;
    text-decoration: none;
}

body.night-mode {
    background: #181b23;
}

.night-mode li a {
    color: #fff !important;
}
<div class="fixed-darkmode">
            <div class="darkmode-definition">
                        <button class="nightModeButton">darkmode</button>
            </div>

 
 <nav style="padding-left: 100px;">
                        <ul>
                            <li><a href="#">Bio</a></li>
                            <li><a href="#">Galéria</a></li>
                        </ul>
                    </nav>

Upvotes: 4

Related Questions