1

i already set the background color in css file , and iwant to read it and change by javascript var backgroundColor = document.querySelector("body").style.backgroundColor;

if change the color it works , but I want to store the value and use it in if contiditon

3 Answers3

1

Try using getComputedStyle.

const backgroundColor = getComputedStyle(document.querySelector("body")).backgroundColor
Troy Carlson
  • 2,965
  • 19
  • 26
1

.style only works for defined inline styles. You need to use .getComputedStyle(ele):

 var backgroundColor = getComputedStyle(document.querySelector("body")).backgroundColor;

Also consider document.stylesheets.

Chong Lip Phang
  • 8,755
  • 5
  • 65
  • 100
0

You can change background color by following ways-

  1. if you want to change background color by body tag

     document.body.style.backgroundColor = "red";
    
  2. if want to change background color of an element Id

     document.getElementById("myDiv").style.backgroundColor = "lightblue";
     document.getElementById("myDiv").style.backgroundColor = "#ffffff";
    
  3. if you are using jquery

    $("#myDiv").css( "background-color", "green");