0

The written code works only on the first button. How to make it work for the second and every subsequent one. Supposedly the forEach method, but I feel a bit lost in it. Thanks in advance.

const btns = document.querySelector(".btn")
const div = document.querySelector(".one")

const change = () => {
  div.style.backgroundColor = "black"
}
btns.addEventListener("click", change)
body {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 25px;
}

.one {
  margin: 20px;
  width: 200px;
  height: 200px;
  color: blue;
  background-color: red;
}

.btn {
  padding: 10px;
  margin: 1em;
  background-color: blue;
}

.form {
  flex-direction: column;
  margin: 2em;
}
<div class="box">
  <div class="one">first</div>
  <div class="btn">first button</div>
</div>
<div class="box">
  <div class="one">second</div>
  <div class="btn">second button</div>
</div>
<div class="box">
  <div class="one">third</div>
  <div class="btn">third button</div>
</div>
isherwood
  • 58,414
  • 16
  • 114
  • 157

2 Answers2

1

QuerySelector will return you the first corresponding element. In order to have an array, use querySelectorAll.

For the same reason, your change callback will only modify the first .one element. This code should do the trick :

const btns = document.querySelectorAll('.btn');

btns.forEach(b => {
b.addEventListener("click", function(e){
   let div = e.target.closest(".box").querySelector(".one");
   div.style.backgroundColor="black";
})
});
SyFi
  • 11
  • 2
-1

Try .forEach

const btns=document.querySelectorAll(".btn")

Instead of:

btns.addEventListener("click", change)

Try:

btns.forEach(button=>button.addEventListener("click", change))
ProfDFrancis
  • 8,816
  • 1
  • 17
  • 26