Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

206
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda