Javascript Reference - HTML DOM Style backgroundColor Property








The backgroundColor property sets or gets the background color of an element.

Browser Support

backgroundColor Yes Yes Yes Yes Yes

Syntax

Return the backgroundColor property:

object.style.backgroundColor

Set the backgroundColor property:

object.style.backgroundColor=color|transparent|initial|inherit

Property Values

Value Description
color Specifies the background color.
transparent Default. The background color is transparent.
initial Set to default value.
inherit Inherit from parent element.




Technical Details

Default Value: transparent
Return Value: A string representing the background color
CSS Version CSS1

Example

The following code shows how to set a background color


<!DOCTYPE html>
<html>
<body>
<h1>Hello World!</h1>
<button type="button" onclick="myFunction()">test</button>
<script>
function myFunction() {<!--from   w ww . jav  a2s .c  o m-->
    document.body.style.backgroundColor = "blue";
}
</script>
</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to set a background color for a <div> element.


<!DOCTYPE html>
<html>
<head>
<style> 
#myDIV {<!--   w w w. j  a va  2  s .c  om-->
    width: 300px;
    height: 300px;
    background-color: red;
    color: white;
}
</style>
</head>
<body>
<button onclick="myFunction()">test</button>
<div id="myDIV">Hello</div>
<script>
function myFunction() {
    document.getElementById("myDIV").style.backgroundColor = "blue";
}
</script>

</body>
</html>

The code above is rendered as follows:

Example 3

The following code shows how to get the background color from a <div> element.


<!DOCTYPE html>
<html>
<body>
<div id="myDiv" style="background-color:orange;">This is a div element.</div>
<button type="button" onclick="myFunction()">test</button>
<script>
function myFunction() {<!--   ww w  .ja  v  a2s .c  o  m-->
    console.log(document.getElementById("myDiv").style.backgroundColor);
}
</script>
</body>
</html>

The code above is rendered as follows:

Example 4

The following code shows how to get the background color for body tag.


<!DOCTYPE html>
<html>
<body style="background-color:yellow;">
<button type="button" onclick="myFunction()">test</button>
<script>
function myFunction() {<!-- w w  w.  j a va 2s . co m-->
    console.log(document.body.style.backgroundColor);
}
</script>

</body>
</html>

The code above is rendered as follows: