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

217
Views
¿Cómo eliminar una clase cuando se hace clic en otro elemento?

Quiero crear una galería simple. Cuando se hace clic en la imagen, se cambia de tamaño. Sin embargo, cuando hago clic en otra imagen, la primera sigue activa. ¿Cómo elimino la clase cuando hago clic en otra imagen?

 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 answers
Answer question

0

sin complicarlo, puede restablecer eliminar bigger de todas las imágenes y configurarlo en la imagen en la que se hizo clic

 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 Report

0

Hay varios enfoques para algo como esto. Una forma sería simplemente encontrar el elemento seleccionado previamente y eliminar la clase cuando se haga clic en uno nuevo:

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

En contexto, esto podría verse así:

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