简体   繁体   中英

Having trouble changing classes to diferent tags of html with js and css

I was trying to do the same thing to body but for other tags like button, fieldset, etc

The way to change the body tag for darkmode is "document.body.classList.add("darkmode");" but i need to know the same thing but for other tags like the ones i named before.

My JS code

let darkMode = localStorage.getItem("darkMode");

const enableDarkMode = () => {
    document.body.classList.add("darkmode");
    localStorage.setItem("darkMode", "enable");
}

const disableDarkMode = () => {
    document.body.classList.remove("darkmode");
    localStorage.setItem("darkMode", null);
}

if(darkMode === "enable"){
    enableDarkMode()
}

$("#dark_mode_toggle").click(() => { 
    darkMode = localStorage.getItem("darkMode");
    if (darkMode !== "enable"){
        enableDarkMode();
    }else{
        disableDarkMode();
    }
});

Kinglish's suggestion in the comments does seem right, after all CSS stands for Cascading StyleSheets, but here is a JS solution to what you were asking for.

Since it seems like you are using JQuery, you can do this:

$("button").addClass("darkmode");

Without JQuery, you can do this:

document.querySelectorAll("button").forEach(element => element.classList.add("darkmode"));

For other elements, like fieldset, just repeat the code you chose to use from above. I think it should be trivial to figure out how to disable the dark mode using the code you already have and this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM