Home > other >  get nth number of div in loop
get nth number of div in loop

Time:11-27

Hi i wanted to know how would i get nth of each div

I added comments in the code on what i want to do

Thanks

    <div class = "card">div1</div>
    <div class = "card">div2</div>
    <div class = "card">div3</div>
    <div class = "card">div4</div>
    <div class = "card">div5</div>
    <div class = "card">div6</div>
    <div class = "card">div7</div>
    <div class = "card">div8</div>
    <div class = "card">div9</div>
    <div class = "card">div10</div>
    <div class = "card">div11</div>
    <div class = "card">div12</div>
    so on .........

    $(".card").each(function (i, card) {

      if(div1, div4, div7, div10, ...)
      //do stuff
      else (div2, div5, div8, div11,  ...)
      //do stuff
      else (div3, div6, div9, div12, ...)

    });

CodePudding user response:

Try using the :nth-child() pseudo selector.

div {
  height: 50px;
  width: 100%;
}

div:nth-child(3n 1) {
  background-color: red;
}

div:nth-child(3n 2) {
  background-color: blue;
}

div:nth-child(3n 3) {
  background-color: green;
}
<div class="card">div1</div>
<div class="card">div2</div>
<div class="card">div3</div>
<div class="card">div4</div>
<div class="card">div5</div>
<div class="card">div6</div>
<div class="card">div7</div>
<div class="card">div8</div>
<div class="card">div9</div>
<div class="card">div10</div>
<div class="card">div11</div>
<div class="card">div12</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can use modulo on the index i, such as i % n where n is the different number of cases you want to check for. For example, if we wanted to break into four (4) conditions -

$(".card").each(function (i, card) {
  if (i % 4 == 0)
    // ...
  else if (i % 4 == 1)
    // ...
  else if (i % 4 == 2)
    // ...
  else if (i % 4 == 3)
    // ...
})

for (let i=0; i<20; i  )
  console.log(i, i%4)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

i i % 4
0 0
1 1
2 2
3 3
4 0
5 1
6 2
7 3
8 0
9 1
10 2
11 3
12 0
13 1
14 2
15 3
16 0
17 1
18 2
19 3
  • Related