Javascript function toggling CSS classes not working (light/dark mode)

I have created a light/dark mode toggle on a web page. The toggle itself is an image that when clicked changes the page background color and text color, as well as a handful of incidentals like an image background color change. When the image is clicked it called a JS function that toggled a class for each element that needed changing. Initially I had a function for each element with a unique class to trigger the various changes, and it worked, however I wanted to streamline the function and have all the elements share a "light/dark mode" class so on function could toggle them all. Now however the code doesn’t seem to respond as intended. I’m pretty new to JavaScript so I’m sure it’s an obvious mistake on my end. A different script does work on the page so the page is linking the .js file correctly. Please see my code below. I have edited out what I believe are unrelated portions. If there’s a better way to do any of this I’m all ears. Thank you!

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="styles.css">
</head>
<body class="light-mode">
    <span class="light-switch-span">
      <img class="light-switch light-mode" src="idea.png" onclick="lightMode()">
    </span>
    <script src="myScript.js"></script>
    <div class="photo-div">
      <img class="photo light-mode" src="img.png"></div>
    </div>
  </body>
</html>
/* CSS */

body {
    margin: 0;
    font-family: 'Poppins';
    background-color: black;
    color: white;
}

body.light-dark {
    background-color: white;
    color: black;
    transition: 0.5s;
}

.light-switch-span {
    padding: 0;
}

.light-switch {
    width: 2.5%;
    height: auto;
    position: absolute;
    right: 0%;
    object-fit: contain;
    margin-right: 5%;
    transition: filter .5s ease-in-out;
}

.light-switch.light-dark {
    -webkit-filter: grayscale(0%);
    filter: grayscale(0%);
}

.photo {
    object-fit: contain;
    height: auto;
    width: 100%;
    border: 10px solid;
    border-radius: 50%;
    background-color: white;
    transition: filter .5s ease-in-out;
    -webkit-filter: grayscale(100%);
    filter: grayscale(100%);
}

.photo.light-dark {
    background-color: black;
}

// JavaScript

function lightMode() {
    var all = document.querySelector(".light-mode");
    for(var i = 0; i < all.length; i++) {
        element.classList.toggle("light-dark");  
    }
}

>Solution :

First, you have to use the querySelectorAll method to get all the matched elements

And, where do you get the element variable ? i think you try to do this

function lightMode() {
    var all = document.querySelectorAll(".light-mode");
    for(var i = 0; i < all.length; i++) {
        // replace element for all[n]
        all[i].classList.toggle("light-dark");  
    }
}

Leave a Reply