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

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

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 Report

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