Javascript Reference - HTML DOM Style backgroundImage Property








The backgroundImage property sets or gets the background image of an element.

Browser Support

backgroundImage Yes Yes Yes Yes Yes

Syntax

Return the backgroundImage property:


var v = object.style.backgroundImage 

Set the backgroundImage property:

object.style.backgroundImage=url('URL')|none|initial|inherit

Property Values

url('URL')
Image URL. To specify more than one image, separate the URLs with comma.
none
(Default.) No background image.




Technical Details

Default Value: none
Return Value: A string representing the background image
CSS Version CSS1

Example

The following code shows how to set a background image for a document.


<!DOCTYPE html>
<html>
<body>
<h1>Hello World!</h1>
<button type="button" onclick="myFunction()">test</button>
<script>
function myFunction() {<!-- www.ja  v a2  s  .c  o m-->
    document.body.style.backgroundColor = "#f3f3f3";
    document.body.style.backgroundImage = "url('http://java2s.com/style/demo/border.png')";
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to set a background image of a specific <div> element.


<!DOCTYPE html>
<html>
<head>
<style>
div {<!--   ww w .  ja  v  a 2s  . co m-->
    width: 400px;
    height: 400px;
    border: 1px solid black;
}
</style>
</head>
<body>

<h1>Hello World!</h1>

<div id="myDiv">This is a div element.</div>
<button type="button" onclick="myFunction()">test</button>
<script>
function myFunction() {
    document.getElementById("myDiv").style.backgroundImage = "url('http://java2s.com/style/demo/border.png')";
}
</script>

</body>
</html>

The code above is rendered as follows:

Example 3

The following code shows how to get the background image of a specific <div> element.


<!DOCTYPE html>
<html>
<body>
<!--  w  ww .j  a v  a  2  s  .c om-->
<h1>Hello World!</h1>

<div id="myDiv" style="background-image:url('http://java2s.com/style/demo/border.png');border:1px solid black;height:400px;width:400px;">This is a div element.</div>
<button type="button" onclick="myFunction()">test</button>

<script>
function myFunction() {
    alert(document.getElementById("myDiv").style.backgroundImage);
}
</script>

</body>
</html>

The code above is rendered as follows:

Example 4

The following code shows how to get the background image of a document.


<!DOCTYPE html>
<html>
<body style="background:#f3f3f3 url('http://java2s.com/style/demo/border.png');">
<!--from   w  w w. j  a va 2  s. c  om-->
<h1>Hello World!</h1>
<button type="button" onclick="myFunction()">test</button>
<script>
function myFunction() {
    console.log(document.body.style.backgroundImage);
}
</script>
</body>
</html>

The code above is rendered as follows: