Skip to content Skip to sidebar Skip to footer

Switching Between Two Background Colors Of A Web Page With Css Switch

my code works fine I just need to switch between two colors white and black I need help to modify the JavaScript code to turn switch between white and black colors. -CSS

Solution 1:

getElementsByClassName() returns an html collection object. It is a collection. If you want to find the first element with the class, you need to use the index [0] like below -

document.getElementById("tog-bg").addEventListener('click', function(){
    document.getElementsByClassName("mainWrapper")[0].style.backgroundColor = document.getElementById("tog-bg").checked ? "white" : "black";
});

If you want to do this for all elements with the specified class, then you can loop it like below -

document.getElementById("tog-bg").addEventListener('click', function(){
    for(let i = 0; i < document.getElementsByClassName("mainWrapper").length; i++){
        document.getElementsByClassName("mainWrapper")[i].style.backgroundColor = document.getElementById("tog-bg").checked ? "white" : "black";
    }
});

I am using the ternary operator instead of if else condition in the above snippet. Also, I have replaced the change event with click event in the listener.

Solution 2:

getElementByClassName returns collection

So code should be

//add [0] to both getElementByClassNamedocument.getElementsByClassName("mainWrapper")[0].style.backgroundColor

Also there isn't any class mainWrapper here so you should create a parent div with class mainWrapper

Solution 3:

This worked for me in firefox (not styled, but functional) :

document.getElementById("tog-bg").onclick = function(){
      var e;
    if( (e = document.getElementById("tog-bg")).hasAttribute('checked')) {
      var w = document.getElementsByClassName("mainWrapper ");
      for(i=0;i<w.length;++i)
      {
        w[i].style.backgroundColor = "black";
      }
      e.removeAttribute('checked');
    } else {
      var w = document.getElementsByClassName("mainWrapper ");
      for(i=0;i<w.length;++i)
      {
        w[i].style.backgroundColor = "white";
      }
      e.setAttribute('checked','');
    }
  };

Post a Comment for "Switching Between Two Background Colors Of A Web Page With Css Switch"