Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

184
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda