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

How to change in javascript background color from css

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.

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 :

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.

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