Home > OS >  How to change in javascript background color from css
How to change in javascript background color from css

Time:11-29

I'm having problems changing the css in javascript. Here's what i tried making:

<style id="1">
body {
background-color: pink;
}
</style>
<script>
var myVar = document.getElementById("1").style.backgroundColor = "brown";
</script>

The css is working, it is making the background pink, but the javascript isn't changing the css background color to brown.

CodePudding user response:

You are attempting to set the background colour of the <style> tag. This is not how it works. Instead of setting the style of the <style> tag, you should set the style of the body itself. This W3Schools Article gives an explanation if you need one.

<head>
    <style>
        body {
            background-color: pink;
        }
    </style>
</head>

<body id="1">

    <script>
        document.getElementById("1").style.backgroundColor = "brown";
    </script>
</body>

It's also worth noting you don't need to assign the element to a variable unless you are going to use it later.

CodePudding user response:

You can try This :

var myVar = document.getElementById("1").style.backgroundColor = "brown";
 body {
          background-color: pink;
       }
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
</head>
<body id="1">
      
</body>
</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Use document.body.style.backgroundColor = "brown";, you can't put ids' or classes on non-elements. Try this;

var myVar = document.body.style.backgroundColor = "brown";
body {
background-color: pink;
}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

This selects the body element, you could also put id = "1" on the body element.

CodePudding user response:

You have to set up the property over the selected element, in this case myVar

var myVar = document.getElementById("1");
myVar.style.backgroundColor = "brown";

Also tags should be in HTML, not in style:

<html>
<body  id="1">
ok
</body>
</html>

CodePudding user response:

you cant give the style Tag an ID. It is used to style the page inside the html file. And Body Tag is always unique. So you should not give that tag an ID. Just try to get the body tag in your javascript and change the background-color.

thx Kinglish for your information

CodePudding user response:

Here is how I'd change the body's background color with javascript.

document.querySelector("body").style.backgroundColor = "brown";
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related