Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Im trying to change the background of a CSS "body" property with JS…I keep getting a console error of "newBgColor is not defined"

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading