Hello :) I'm coding dark mode switch and I came across a problem I can't figure out.
I loop through an array which contains items looking like that: { className: 'h3dark', elementId: 'h2'}. Then I use forEach loop to apply each class to ALL elements with a defined ID. Unfortunately it's applying each class on only first html element with an ID. Do you know how it can be fixed?
HTML
<h1 id="h1" class="h1">COLOR</h1> <!--Color changed-->
<h1 id="h2" class="h1">COLOR</h1> <!--Color changed-->
<h1 id="h3" class="h1">COLOR</h1> <!--Color changed-->
<h1 id="h1" class="h1">COLOR</h1> <!--Color not changed-->
<h1 id="h2" class="h1">COLOR</h1> <!--Color not changed-->
<h1 id="h3" class="h1">COLOR</h1> <!--Color not changed-->
<button onclick="darkSwitch()">CHANGE COLOR</button>
</div>
JAVASCRIPT
// checking if cookie exists
var cookieState = Cookies.get('darkMode');
// First visit - cookieState is undefined
// If cookie exists we are parsing it to get a boolean
if(cookieState === undefined) {
var isDarkmodeEnabled = false;
} else {
var isDarkmodeEnabled = JSON.parse(cookieState)
};
// Cookie doesn't exist: darkMode = false
// Cookie exists: darkMode = true/false
var darkMode = isDarkmodeEnabled;
// Add dark mode classes and elements' ids
// className - a name of a class with dark mode attributes
// elementId - an id of an element a class will be added to
var darkClasses = [
{ className: 'h1dark', elementId: 'h1'},
{ className: 'h2dark', elementId: 'h3'},
{ className: 'h3dark', elementId: 'h2'},
];
// Adding classes on page load if darkmode is enabled
window.onload = addClassesOnLoad();
// Changing darkMode state and adding or removing classes
function darkSwitch() {
// Setting darkMode to its opposite value
darkMode = !darkMode;
if(darkMode === true) {
// Looping through an array and deleting classes
darkClasses.forEach(item => {
document.getElementById(item.elementId).classList.add(item.className)
});
} else {
// Looping through an array and deleting classes
darkClasses.forEach(item => {
document.getElementById(item.elementId).classList.remove(item.className)
});
};
// Saving darkMode state to the cookie
Cookies.set('darkMode', darkMode);
}
// Adding classes on page load if darkmode is enabled
function addClassesOnLoad() {
if(darkMode === true){
darkClasses.forEach(item =>{
document.getElementById(item.elementId).classList.add(item.className)
});
};
}