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

130
Vistas
Image src won't change using JavaScript

I feel like I have this right, but for some reason, the addEventListener isn't functioning how I want it to. When I try to change the img.src below, it still only shows the 'images/expand.jpeg' img. I have confirmed that the path to the image is correct, as it does show the 'images/collapse.png' when I change the button's original src to 'images/collapse.png'.

document.querySelectorAll('.title').forEach(function(){
    let button = document.createElement('img');
    button.classList.add('smallbutton');
    button.src = "images/expand.jpeg"; 
    eachTitleDiv.append(button);
    button.addEventListener('click', function(){
        if (button.src === "images/expand.jpeg") {
            button.src = "images/collapse.png";
        } else if (button.src === "images/collapse.png") {
            button.src = "images/expand.jpeg";
        };
    });
});
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Relative src attribute computes to absolute URL in the DOM

  1. When you access the src attribute, it's the computed DOM value, and your relative link was computing to the absolute link. (https://yourwebsite.com/images/expand.jpeg === "images/expand.jpeg") returns false
  2. ALWAYS have an alt on your images, like in this case where they don't load, for visually impaired, SEO so many reasons!

Here is a working snippet where the alt is used to check state rather than the src:

document.querySelectorAll('.title').forEach(function(eachTitleDiv){
    let button = document.createElement('img');
    button.classList.add('smallbutton');
    button.src = "images/expand.jpeg";
    button.alt = "expand"
    eachTitleDiv.append(button);
    button.addEventListener('click', (e) => {
        if (button.alt === "expand") {
            button.src = "images/collapse.png";
            button.alt = "collapse"
        } else if (button.alt === "collapse") {
            button.src = "images/expand.jpeg";
            button.alt = "expand"
        };
    });
});
<h1 class="title">Title 1</h1>
<h2 class="title">Title 2</h2>
<p>Not a title</p>

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