Home > Software engineering >  Give a class based on the return of a number in the loop
Give a class based on the return of a number in the loop

Time:12-12

For example, I want to apply a separate css to the 7th, 14th and 21st ... items in the loop. How do I do this?

    var items = document.querySelectorAll('.item');   
          
    for(let j = 0; j < items.length; j  ) {

        if() {     
            items[j].style.height = "300px";
        } 
    }

We used such a loop and what kind of query should we use to reach the desired items?

CodePudding user response:

So for this you would use remainder operator. You can check it out here

This would make your code like this

const items = document.querySelectorAll('.item');   
      
for(const j = 0; j < items.length; j  ) {

    if(j % 7 === 0) { 
        // if the remainder of j/7 is 0
        // i.e j=0,7,14,...
        // since j starts at 0, you can ignore 0 by adding j !== 0 to the condition

        items[j].style.height = "300px";
    } 
}

CodePudding user response:

You can try CSS :nth-child() Selector, it's powerful and easy to understand https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child

    .item:nth-child(7), .item:nth-child(14), .item:nth-child(21) {
      height: 300px;
    }
  • Related