vendredi 20 août 2021

Setting src through DOM vs Comparing src values

I have an img tag like this

<img id="fish" src="">

And I set and changed the src of img throught a setInterval function randomly

var randFish = Math.floor(Math.random() * 2);

if(randFish == 0) document.getElementById('fish').src = "images/fish.png";
else if(randFish == 1) document.getElementById('fish').src = "images/fishbone.png";

This piece of code works well and image path is added successfully to the src, but when I try to compare if this src is equal to that path, it returns false always

console.log(document.getElementById('fish').src == "images/fish.png"); //output: false
console.log(document.getElementById('fish').src == "images/fishbone.png"); //output: false

When I try to return in console the src

console.log(document.getElementById('fish').src); //output: file:///C:User/Desktop/.../images/fishbone.png

Using path of image this way to compare works, but why this happens and is there a clever solution than using the entire path like "file:///C:User/Desktop/.../images/fishbone.png"

Aucun commentaire:

Enregistrer un commentaire