How to change background color using JavaScript?

In this tutorial, we will learn how to change the background color using JavaScript.

The backgroundColor property in JavaScript is used to change the background color to given color.

We are going to create an HTML page and set the background color of the body to red using the backgroundColor property.

  • Changing background color of the body to red:

<!DOCTYPE html>
<html>
<head>
    <title>Codespeedy</title>
</head>
<body>
    <script type="text/javascript">
        document.body.style.backgroundColor = 'red';
    </script>
</body>
</html>
  • getting element by its id using getElementById() function and changing color using backgroundColor property.

getElementById()-  This function is used to get an element using its id.

getElementsByClassName()- This function is used to get an element using its class.

Using the above function, we are going to get an element by its id and set its background color using backgroundColor  property.

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <p id=ID12'>
        CodeSpeedy 
    </p>
    <script type="text/javascript">
        document.getElementById('ID12').style.backgroundColor = 'red';
    </script>
</body>
</html>

This HTML code will not change the background color of the entire page, but only change the background color of the element with id ‘ID12’.

  •  changing the background color of a text using a button

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<button onClick="Mycolor()">Change Color using button</button>
<div id="ID12">CodeSpeedy</div>
<script type='text/javascript'>
function Mycolor() {
var elementtochange = document.getElementById("ID12");
elementtochange.style.backgroundColor='#900';
}
</script>
</body>
</html>

The background color of the text will change when we press the button.

Leave a Reply

Your email address will not be published.