Changing the image of a Section using javascript

Asked

Viewed 49 times

2

I have a section that contains in your file .css the following:

.cid-qTkA127IK8 {
   background-image: url("../../../assets/images/background4.jpg");
}

However, my goal is instead to use the CSS to insert images, I would like to insert the link to a URL in a input form and, through the Javascript, add this background image of tag section.

In order to test the selectors of the Javascript, I initially tried to change the color and it worked, however, I can not change the image...

<section class="cid-qTkA127IK8 mbr-fullscreen mbr-parallax-background" id="header2-1">
    <script>
        document.getElementById('header2-1').style.backgroundImage ="https://jornaldoempreendedor.com.br/wp-content/uploads/2018/05/xd_070318_454_4243.jpg";
    </script>
</section>

I even tried to change the image by selecting the class selector Javascript, but I still didn’t succeed.

Another way too, that I tried to change the address of the image was by using the src selector, as follows:

document.getElementsByClassName("cid-qTkA127IK8").src= "https://jornaldoempreendedor.com.br/wp-content/uploads/2018/05/xd_070318_454_4243.jpg";

Likewise, I had no results.

1 answer

3


You need to put the attribute url() and insert the link inside the image to render, but, what you want to do is not very nice, because depending on the image can take to load, the most indicated is to leave the images in a local folder:

document.getElementById('header2-1').style.backgroundImage = 'url("https://jornaldoempreendedor.com.br/wp-content/uploads/2018/05/xd_070318_454_4243.jpg")';
#header2-1 {
  height: 1000px;
  width: 1000px;
}
<section class="cid-qTkA127IK8 mbr-fullscreen mbr-parallax-background" id="header2-1">
</section>

  • I was late :D

  • 1

    @hugocsl I waited for you ;)

  • it is also worth remembering that to use the function getElementsByClassName it is necessary to inform the position (because it returns an array). If it is the only element with this class, it would use Document.getElementsByClassName("Cid-qTkA127IK8")[0]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.