Local storage value saved but how to use the saved local storage used. I tried creating a function apply but the class is not applying
document.querySelectorAll("#abc, #xyz").forEach(btn => {
btn.addEventListener("click", () => {
const e = document.querySelectorAll(".dog,.cat, #abc, #xyz");
e.forEach(el => {
el.classList.toggle("red");
var xyz = document.getElementById("xyz").className;
localStorage.setItem("vovo", xyz);
});
});
})
function apply(){
var xy = localStorage.getItem('vovo');
if (xy) {
var single = document.querySelectorAll(".dog,.cat, #abc, #xyz");
single.forEach(el => {
el.classList.add(xy);
});
}
};
The functionality logic :
button
is pressed we check if it has thered
class (as all the elements,button
s and the otherdiv
s, will receive thered
class at some point).button
s and the otherdiv
s) thus thelocalStorage
will store something like "No the elements don't have the red class".button
s and the otherdiv
s) thus thelocalStorage
will store something like "Yes the elements have the red class".localStorage
will store'0'
if the class isn't applied,'1'
if the class is applied.now, when the page gets refreshed, we check if the
localStorage
item that stores thered
class' state is there (notnull
) and has the value of'1'
then apply that class to all the elements (thebutton
s and the otherdiv
s).remove the item that holds the
red
class' state from thelocalStorage
.Here's the update
JavaScript
code :just use the following syntax:
If you want to read the value instead: