JavaScript Change the Background Color of HTML Element

To change the background color of a HTML Element using JavaScript, get reference to that HTML element, and assign required color value to the element.style.backgroundColor property.

In the following example, we will change the background color of HTML Element with id "myElement" to the color "#00FF00", in JavaScript, using element.style.backgroundColor property.

example.html

<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        #myElement {
            border:1px solid;
            width:100px;
            height:100px;
            background: #CCC;
        }
    </style>
    <meta charset="utf-8">
</head> 
<body>
    <h2>Change Background Color of HTML Element in JavaScript</h2>
    <div id="myElement"></div>
    <br>
    <button type="button" onclick="changeStyle()">Click Me</button>
    <script>
    function changeStyle(){
        var element = document.getElementById("myElement");
        element.style.backgroundColor = "#00FF00";
    }
    </script>
</body>
</html>

Conclusion

In this JavaScript Tutorial, we learned how to change the background color of a HTML Element using JavaScript.