Home > Mobile >  Loop through items and target first 3 and last items seperately
Loop through items and target first 3 and last items seperately

Time:01-17

Is there a better way to write this for loop?

  1. I am basically looping through a collection of divs. (The number of divs can increase and decrease dynamically, so it's never a set number).
  2. If the length of the collection is greater than 4, I want to set flex styling the first 3 items. And I want to set a width on the remaining items, from the 4th item on wards.
  3. If the length of the collection is less than 4, I want to set flex styling on all items.

This works at the most basic level but wondered if there was a smarter way to write this?

let divCount = document.getElementsByClassName("luggage-tile-wrapper active");

for (let i = 0; i < divCount.length; i  ) {
    if (divCount.length > 3) {
        for (let i = 0; i < 3; i  ) {
            divCount[i].style.flex = "1 0 22.2%";
        };
        for (let i = 3; i < divCount.length; i  ) {
            divCount[i].style.width = "145px";
        };
    } else {
        for (let i = 0; i < divCount.length; i  ) {
            divCount[i].style.flex = "1 0 22.2%";
        };
    };
}

Thanks,

CodePudding user response:

Do two loops, one for the first 3, the other for the rest. If there are less than 3 divs, the second loop won't do anything.

let first3 = Math.min(3, divCount.length); // don't go past the end if less than 3
for (let i = 0; i < first3; i  ) {
    divCount[i].style.flex = "1 0 22.2%";
}
for (let i = 3; i < divCount.length; i  ) {
    divCount[i].style.width = "145px";
}

CodePudding user response:

So you always want to do

divCount[i].style.flex = "1 0 22.2%";

for the first 3 items

And for every other item you want

divCount[i].style.width = "145px";

So this is it

for (let i = 0; i < divCount.length; i  ) {
  if (i < 3) {
    divCount[i].style.flex = "1 0 22.2%";
  } else {
    divCount[i].style.width = "145px";
  }
}

CodePudding user response:

I know you've already accepted an answer--and I realize I don't have all the information--but it seems like you could achieve this entirely in css, without any javascript at all.

.container {
  display: flex;
  flex-wrap: wrap;
}

.container > * {
  flex: 1 0 22.2%;
  background: skyblue;
}

.container > :nth-child(1n   4) {
  background: pink;
  width: 145px;
}
<div >
  <div >item</div>
  <div >item</div>
  <div >item</div>
  <div >item</div>
  <div >item</div>
  <div >item</div>
  <div >item</div>
</div>

  • Related