Home > Software engineering >  All the small blocks change color at once querySelectorAll() problem
All the small blocks change color at once querySelectorAll() problem

Time:11-27

When I hover over bigger blocks (the blue ones) all the small block change to black at once.

I want only to change the color of the small block inside the hovered blue block not all of them.

Also, I know with CSS (pseudo-selector, :hover) can do the same but I want to do it with JS as I said this is not my main code.

const smallContainer = document.querySelectorAll(".small-container")
const logoContainer = document.querySelectorAll(".logo-container")

smallContainer.forEach((value) => {
  value.addEventListener("mouseover", () => {
    logoContainer.forEach((valuein) => {
      valuein.classList.remove("logo-container")
      valuein.classList.add("logo-container-animation")
    })
  })
})
.main-container {
  display: flex;
  width: 100%;
  height: 100vh;
  justify-content: space-between;
}

.small-container {
  height: 200px;
  width: 200px;
  background-color: blue;
  transition: all .5s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.logo-container {
  height: 25px;
  width: 25px;
  background-color: rgb(255, 0, 0);
}

.logo-container-animation {
  background-color: rgb(0, 0, 0);
  height: 25px;
  width: 25px;
  transition: all 2s;
}
<div >
  <div ><span ></span></div>
  <div ><span ></span></div>
  <div ><span ></span></div>
  <div ><span ></span></div>
</div>

CodePudding user response:

Prev: Use the index of the hovered element.
Prev Update: I've added an extra snippet in order if you wanted to remove the effect after the mouse leave.
Updated: For selecting whatever red boxes are in the blue box, use querySelectorAll and do an iteration.

const smallContainer = document.querySelectorAll(".small-container")
const logoContainer = document.querySelectorAll(".logo-container")

smallContainer.forEach((value, i) => {
  const logoContainers = value.querySelectorAll(".logo-container")

  value.addEventListener("mouseover", () => {
    /* Prev
      logoContainer[i].classList.remove("logo-container");
      logoContainer.classList.add("logo-container-animation")
    */
    // <!-------- UPDATED:            
  • Related