Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this an even or odd element?

Tags:

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.

like image 716
mrtsherman Avatar asked Oct 06 '11 19:10

mrtsherman


People also ask

How do you know if an element is even?

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.

How do you find the odd element?

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].

How do you know if it's an odd or even number?

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.


2 Answers

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 */ } }); 
like image 88
Sean Vieira Avatar answered Sep 21 '22 06:09

Sean Vieira


$('div').each( function(index) {    //do something different based on whether even or odd div    if (index % 2 == 0) {}  // even    else {} // odd }); 
like image 22
Shef Avatar answered Sep 23 '22 06:09

Shef