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

Issue

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 class="award-winner-wrapper">
    <h2>Heading></h2>
    <p>Paragraph content</p>
    <p>Paragraph content</p>
    <div class="award-winner'></div>
</div>

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

<div class="award-winner-wrapper">
    <h2>Heading></h2>
    <p>Paragraph content</p>
    <p>Paragraph content</p>
    <div class="award-winner'></div>
    <div class="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.

Solution

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 class="award-winner-wrapper">
    <h2>Heading></h2>
    <p>Paragraph content</p>
    <p>Paragraph content</p>
    <div class="award-winner"></div>
</div>

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

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

Answered By – pilchard

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published