TomDev
TomDev

Reputation: 287

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");
  });
}

Upvotes: 0

Views: 844

Answers (2)

Yona Appletree
Yona Appletree

Reputation: 9142

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" />

Upvotes: 0

scr2em
scr2em

Reputation: 1024

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");
  });
}

Upvotes: 2

Related Questions