Home > Blockchain >  Im trying to change the background of a CSS "body" property with JS...I keep getting a con
Im trying to change the background of a CSS "body" property with JS...I keep getting a con

Time:04-28

I have been trying to use a function to change a background color with DOM. I'm probably missing something super "in my face" but I can't see it

My JS code is -

function changeBg()     {     
let newBgColor = document.querySelector("body")      
console.log(newBgColor)      
newBgColor.style.backgroundColor = "white";      
}
The CSS Im hoping to change is -

     body {      
  font-family: 'Open Sans';     
  font-weight: normal;      
  max-width: 760px;      
  background-color: #ffe8d6;      
  margin: 0 auto;      
  color: rgb(193, 178, 164);      

  }
``   
I keep getting this error -
ReferenceError - newBgColor is not defined.

CodePudding user response:

Here is an example of what you could do, load the CSS in the <head> and load the JavaScript at the end of the page.

<!DOCTYPE html>
<html>

<head>
  <title>Body Bg Color</title>

  <style>
    body {
      font-family: 'Open Sans', sans-serif;
      font-weight: normal;
      max-width: 760px;
      background-color: #ffe8d6;
      margin: 0 auto;
      color: rgb(193, 178, 164);
      width: 100vw;
      height: 100vh;
    }
  </style>

</head>

<body>


  <script>
    function beigeBg() {
      let newBgColor = document.querySelector("body")
      console.log(newBgColor)
      newBgColor.style.backgroundColor = "beige";
    }

    beigeBg();
  </script>
</body>

</html>

  • Related