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

205
Vistas
How to remove a class when another element is clicked?

I want to create a simple gallery. When the image is clicked it is resized. However, when I click another image, the first one is still active. How to remove the class when I click another image?

const imgList = document.querySelectorAll("img");
console.log(imgList);
for (let i = 0; i < imgList.length; i++) {
  imgList[i].addEventListener("click", function () {
    imgList[i].classList.toggle("bigger");
  });
}

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

without complicating it you can just reset remove bigger from all images and set it to the clicked image

const imgList = document.querySelectorAll("img");

for (let i = 0; i < imgList.length; i++) {
  imgList[i].addEventListener("click", function () {

    imgList.forEach(el=> el.classList.remove("bigger"))

    imgList[i].classList.add("bigger");
  });
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

There are several approaches to something like this. One way would be simply find the previously selected item and remove the class when a new one is clicked:

    const currentlySelectedElem = document.querySelector("img.bigger");
    if (currentlySelectedElem) {
        currentlySelectedElem.classList.remove("bigger");
    }

In context, this might look something like this:

document.querySelectorAll("img").forEach(imgElem => {
  imgElem.addEventListener("click", function () {

    // Deselect the last selected image by selecting it and removing the class if needed
    const currentlySelectedElem = document.querySelector("img.bigger");
    if (currentlySelectedElem) {
        currentlySelectedElem.classList.remove("bigger");
    }
    
    // Indicate the current selection
    imgElem.classList.add("bigger");
  });
});
img {
  width: 64px;
  height: 64px;
}

img.bigger {
  width: 128px;
  height: 128px;
}
<img src="https://placeimg.com/200/200/any" />
<img src="https://placeimg.com/200/200/any" />
<img src="https://placeimg.com/200/200/any" />
<img src="https://placeimg.com/200/200/any" />
<img src="https://placeimg.com/200/200/any" />

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