Home>

How do I change the backgroundImage of an image?

<div id='photo' style="background-image: url('img/image.png');"> </div><script>  var photo= document.getElementById('photo')
  photo.backgroundImage= url('img/image2.png')
</script>
  • Answer # 1

    Use to allow single or double quotes:

    var photo= document.getElementById('photo');
    photo.style.backgroundImage= `url('img/image2.png')`;
    <div id='photo' style="background-image: url('img/image.png');"> </div>

    Also, lines like this make it easy to insert variables:

    var imagesUrl= ['img/image1.png','img/image2.png','img/image3.png'];
    var photo= document.getElementById('photo');
    photo.style.backgroundImage= `url('${imagesUrl[1]}')`;
    <div id='photo' style="background-image: url('img/image.png');"> </div>

    why not just double quotes?

    Grundy2022-02-02 21:45:07

    @Grundy: For perspective -what if the person decides to use doubles internally :)

    UModeL2022-02-02 21:46:11
  • Answer # 2

    Use to allow single or double quotes:

    var photo= document.getElementById('photo');
    photo.style.backgroundImage= `url('img/image2.png')`;
    <div id='photo' style="background-image: url('img/image.png');"> </div>

    Also, lines like this make it easy to insert variables:

    var imagesUrl= ['img/image1.png','img/image2.png','img/image3.png'];
    var photo= document.getElementById('photo');
    photo.style.backgroundImage= `url('${imagesUrl[1]}')`;
    <div id='photo' style="background-image: url('img/image.png');"> </div>

    why not just double quotes?

    Grundy2022-02-02 21:45:07

    @Grundy: For perspective -what if the person decides to use doubles internally :)

    UModeL2022-02-02 21:46:11