Set a background image of a specific <div> element: - Javascript CSS Style Property

Javascript examples for CSS Style Property:backgroundImage

Description

Set a background image of a specific <div> element:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<style>
div {/* ww  w . ja  v  a 2 s .  c  o 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>
<br>
<button type="button" onclick="myFunction()">Set the background image of div</button>

<script>
function myFunction() {
    document.getElementById("myDiv").style.backgroundImage = "url('http://java2s.com/resources/a.png')";
}
</script>

</body>
</html>

Related Tutorials