Home > Mobile >  The src of img object doesn't work specificly for me
The src of img object doesn't work specificly for me

Time:11-03

im trying to make an src for an img element that i have in my HTML file, but for some reason, when I try to insert a source into an image, the workspace does not recognize the img object as an image object, and therefore does not allow src to be inserted there.

It is important to emphasize that this problem only exists in the work environment I work with (WebStorm). When I tried to put the code into an online work environment, it worked great.

My attempt to put src in WebStorm despite the problem like this:

HTML:

<img id="img" src="https://source.unsplash.com/random">

JS:

let img = document.getElementById("img");
img.src = "https:\/\/images.dog.ceo\/breeds\/terrier-toy\/n02087046_3843.jpg";

But it just made the work environment react with this error:

Cannot set properties of null (setting 'src')

CodePudding user response:

As written in the question, there are 2 (no, 3) options to fix the error.

Option 1: Normal string quote

img.src = "https://images.dog.ceo/breeds/terrier-toy/n02087046_3843.jpg";

Option 2: Add quotes around your original escaped character string

img.src = "https:\/\/images.dog.ceo\/breeds\/terrier-toy\/n02087046_3843.jpg";

Option 3: Set the attribute

img.setAttribute("src", "https://images.dog.ceo/breeds/terrier-toy/n02087046_3843.jpg");

CodePudding user response:

Check out this code. I've added setTimeout for 2 second just to visualize. You can remove setTimeout from here in your case.

function changeImage() {
  setTimeout(function(){
    var image = document.getElementById("img")
    image.src = "https://i.imgur.com/xNE8K6Q.jpeg"
  }, 2000)
}

changeImage()
<html>
  <body>
      <img id="img" src="https://i.imgur.com/hk1iahZ.jpeg" height="100" width="100" />
  </body>
</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Attributes of tags always has the string value so put your url as string. As per your code, you can try this:

let img = document.getElementById("img");
img.src = "https://images.dog.ceo/breeds/terrier-toy/n02087046_3843.jpg";
<img id="img" src="https://source.unsplash.com/random">
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related