i just wonder how to set the background image of a div block after using the queryselector. Below is my test. But none of this work…….Pls help.
JavaScript
x
20
20
1
<!DOCTYPE html>
2
<html>
3
<body>
4
<div class="A">
5
<h1>Hello World!</h1>
6
<button type="button" onclick="myFunction()">Set background image</button>
7
8
9
</div>
10
</body>
11
</html>
12
<script>
13
function myFunction()
14
{
15
document.querySelector(".A").style.background="yellow"; //work
16
document.querySelector(".A").style.setProperty("backgroundImage", "url('2.jpg')")// not work
17
document.querySelector(".A").style.backgroundImage = "url('2.jpg')" //not work
18
}
19
</script>
20
Advertisement
Answer
JavaScript
1
2
1
document.querySelector(".A").style.background="url('2.jpg')";
2
I fully tested that code and it works.