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.
<!DOCTYPE html> <html> <body> <div class="A"> <h1>Hello World!</h1> <button type="button" onclick="myFunction()">Set background image</button> </div> </body> </html> <script> function myFunction() { document.querySelector(".A").style.background="yellow"; //work document.querySelector(".A").style.setProperty("backgroundImage", "url('2.jpg')")// not work document.querySelector(".A").style.backgroundImage = "url('2.jpg')" //not work } </script>
Advertisement
Answer
document.querySelector(".A").style.background="url('2.jpg')";
I fully tested that code and it works.