Home > Enterprise >  Looping through a javascript array to check each item for certain children elements
Looping through a javascript array to check each item for certain children elements

Time:05-20

I am trying to loop through a webpage and change certain styles depending on the number of children with the class 'award-winner' within elements with the class 'award-winner-wrapper'. Currently, I have been able to check the webpage for the parent elements using this.

<div >
    <h2>Heading></h2>
    <p>Paragraph content</p>
    <p>Paragraph content</p>
    <div award-winner-wrapper">
    <h2>Heading></h2>
    <p>Paragraph content</p>
    <p>Paragraph content</p>
    <div award-winner-wrapper">
    <h2>Heading></h2>
    <p>Paragraph content</p>
    <p>Paragraph content</p>
    <div award-winner'></div>
</div>

let parents = document.querySelectorAll('.award-winner-wrapper');
let pArray = Array.from(parents)

The problem I having is using a foreach loop to check each array item for the 'award-winner' class and if there are 2 or more elements with that class change some styles.

CodePudding user response:

Simply iterate over your parents NodeList (here using NodeList.forEach()) and query the parent for relevant children here with querySelectorAll() and adding a class with classList.add()

let parents = document.querySelectorAll('.award-winner-wrapper');

parents.forEach(parent => {
  if (parent.querySelectorAll('.award-winner').length > 1){
    parent.classList.add('winner');
  }
});
.winner {
  background-color: aquamarine;
}
<div >
    <h2>Heading></h2>
    <p>Paragraph content</p>
    <p>Paragraph content</p>
    <div ></div>
</div>

<div >
    <h2>Heading></h2>
    <p>Paragraph content</p>
    <p>Paragraph content</p>
    <div ></div>
</div>

<div >
    <h2>Heading></h2>
    <p>Paragraph content</p>
    <p>Paragraph content</p>
    <div ></div>
    <div ></div>
</div>

  • Related