22

So I saw this question a few moments ago on SO and it got me thinking.

Basically the OP had something along these lines

<div>a</div>
<div>b</div>
<div>c</div>
<div>d</div>
$('div').each( function() {
   //do something different based on whether even or odd div
   if ($(this) == ':even') {}  //invalid markup I know!
   else {}
});

Is there a way to tell inside the .each() whether your current element is an odd or even instance?

There is the .filter method of jQuery, but it always returns true when it has a single element.

I also realize you can use the nth-child selector or set this up in other ways, but I am curious about this specific case.

Community
  • 1
  • 1
mrtsherman
  • 39,342
  • 23
  • 87
  • 111
  • 1
    It's already in the answer to that question. Take a look at the last code snippet: http://stackoverflow.com/questions/7679003/jquery-tigerstipe-rollover-conundrum/7679027#7679027 – BoltClock Oct 06 '11 at 19:32
  • @BoltClock - Thanks, I missed that update. – mrtsherman Oct 06 '11 at 19:36

4 Answers4

63

The callback to .each is passed the element's index and the element:

$('div').each(function(i, el) {
   // As a side note, this === el.
   if (i % 2 === 0) { /* we are even */ }
   else { /* we are odd */ }
});
Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
9
$('div').each( function(index) {
   //do something different based on whether even or odd div
   if (index % 2 == 0) {}  // even
   else {} // odd
});
Shef
  • 44,808
  • 15
  • 79
  • 90
6

If you know that all of the elements are children of the same parent, you can use the index provided by each

$('div').each( function(index) {
    if (index%2 == 0) {}
    else {}
});

otherwise, use the index function which will calculate the index of the element among its siblings.

$('div').each( function() {
    if ($(this).index()%2 == 0) {}
    else {}
});
Dennis
  • 32,200
  • 11
  • 64
  • 79
3

Using Jquery api .is( selector )

$('div').each( function() {
    //Check if element is even
    if ($(this).is(":even")) {
    }

    //Check if element is odd
    if ($(this).is(":odd")) {
    }

});
Hắc Huyền Minh
  • 1,025
  • 10
  • 13
  • This doesn't seem to work. Another user proffered the same solution and has since deleted the answer. Logically it does look promising, but doesn't pan out. http://jsfiddle.net/mrtsherman/EjduK/1/ – mrtsherman Jul 23 '15 at 17:34
  • @mrtsherman: Thanks and yes, i have checked again and found it doesn't work for jquery version < 1.10.1. You have jquery 1.6.3 in your jsfiddle link. – Hắc Huyền Minh Jul 24 '15 at 07:38