Javascript DOM CSS Style backgroundImage Property set for <div>

Introduction

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

document.getElementById("myDiv").style.backgroundImage = "url('background1.png')";

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
div {/*  w w  w.j a  va 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('background1.png')";
}
</script>

</body>
</html>



PreviousNext

Related