Home > Back-end >  How to select even elements by class name with JavaScript?
How to select even elements by class name with JavaScript?

Time:09-21

I've been trying to change color of these divs through a click of a button. But I've been unable to select the EVEN divs like in CSS -> nth-child(even).

Help me select oonly even divs with class name 'newBox'. Thank You

const mainContainer = document.querySelector('.main_box');

for (let i = 0; i < 10; i  ) {
  const newBox = document.createElement('div');
  newBox.classList.add('newBox');
  mainContainer.appendChild(newBox);
}

function change() {
  //I want here to select only the even divs
  document.querySelectorAll('.newBox').forEach((divs) => {
    divs.style.backgroundColor = "green";
  })
}

CodePudding user response:

You must use :nth-child selector like this

document.querySelectorAll('.newBox:nth-child(even)')

read more about it in W3Schools

By the way this is duplicate

CodePudding user response:

Use document.querySelectorAll('.newBox:nth-child(even)')

<div ></div>
.newBox {
    height: 10px;
    background-color: wheat;
}
const mainContainer = document.querySelector('.main_box');

for (let i = 0; i < 10; i  ) {
    const newBox = document.createElement('div');
    newBox.classList.add('newBox');
    mainContainer.appendChild(newBox);
}

function change() {
    document.querySelectorAll('.newBox:nth-child(even)').forEach((divs) => {
       divs.style.backgroundColor = "green";
   })
}
change();
  • Related