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.
A number is even if, when divided by two, the remainder is 0. A number is odd if, when divided by 2, the remainder is 1.
1) Find the middle index, say 'mid'. 2) If 'mid' is even, then compare arr[mid] and arr[mid + 1]. If both are same, then there is an odd occurrence of the element after 'mid' else before mid. 3) If 'mid' is odd, then compare arr[mid] and arr[mid – 1].
A number which is divisible by 2 and generates a remainder of 0 is called an even number. An odd number is a number which is not divisible by 2. The remainder in the case of an odd number is always “1”. The property by which we classify an integer in math as even or odd is also known as parity.
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 */ } });
$('div').each( function(index) { //do something different based on whether even or odd div if (index % 2 == 0) {} // even else {} // odd });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With