1
votes

I want to toggle all "theme" tags in my page from light to dark and from dark to light.

<div theme="light" id="switch-theme" class="switch-btn">

this is my button which upon clicking should switch every "theme" tag on the page to the desired color mode.

I tried:

    <div theme="light" id="switch-theme" class="switch-btn" 

onclick="this.setAttribute('theme', this.getAttribute('theme') === 'dark' ? 'light' : 'dark')">

but this only toggles the button to dark, not EVERY theme attribute on the page.

Can anyone help me?

2

2 Answers

1
votes

To make that work you have to add the click handler function to all the elements. Also, I will suggest you not use inline click handler function, instead you can attach the events with addEventListener() like the following way:

//get all the elements with class switch-btn
var btnList = document.querySelectorAll('.switch-btn');
//loop through them
btnList.forEach(function(btn){
  //attach the event to the current element
  btn.addEventListener('click', function(){
    //clear the console
    console.clear();
    //set the attribute
    this.setAttribute('theme', this.getAttribute('theme') === 'dark' ? 'light' : 'dark');
    //test
    console.log(`Element at index ${Array.prototype.slice.call(btnList).indexOf(btn)}, theme ${this.getAttribute('theme')}`)
  });
});
<div theme="light" class="switch-btn">Div 1</div>
<div theme="light" class="switch-btn">Div 2</div>
0
votes

here is also another approach based on your code switching theme attribute value to all elements at once :

let btn = document.querySelector("#switch-theme");

btn.addEventListener("click", function() {

  let theme = document.querySelectorAll("[theme]");
  for (let i = 0; i < theme.length; i++) {
    theme[i].setAttribute('theme', theme[i].getAttribute('theme') === 'dark' ? 'light' : 'dark')
  }
});
.switch-btn {
  appearance: button;
  display: inline-block;
}

[theme="dark"] {
  background: black;
  color: white;
}
<div  id="switch-theme" class="switch-btn">Switch theme</div>
<div theme="light"> Theme boxe</div> 
<div theme="light">Theme boxe</div>
<div theme="light"> Theme boxe</div> 
<div theme="light">Theme boxe</div>