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"
const img_ = document.getElementById('img_');
img_.fish_ = ['fish.png', 'fishbone.png'];
img_.path_ = 'images/';
img_.change_ = function(){
let random_ = Math.floor(Math.random() * this.fish_.length);
img_.src = `${this.path_}${this.fish_[random_]}`;
console.clear(); console.log(img_.src);
}
<img id="img_" src="" />
<button onclick="img_.change_();">Randomly change fish</button>
<!--
/ = Root directory
. = This location
.. = Up a directory
./ = Current directory
../ = Parent of current directory
../../ = Two directories backwards
-->
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.