Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
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"

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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
-->

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!