Search code examples
javascriptif-statementdombooleansrc

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"


Solution

  • This is because, as you saw when you tried

    console.log(document.getElementById('fish').src);
    

    the element.src property returns the full url of the element. What you are looking for is the value of the src attribute. So try:

    console.log(document.getElementById('fish').getAttribute('src') == "images/fish.png"); 
    

    which should return true.