Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - selecting only every 2nd element with .each?

Tags:

jquery

Is it possible to only select every 2nd element with the .each() function? If not, what alternatives are there?

like image 900
Mathias Lykkegaard Lorenzen Avatar asked Aug 05 '11 11:08

Mathias Lykkegaard Lorenzen


3 Answers

You can use the :odd selector:

$("yourSelector:odd").each(function() {
    // Will be called on every second element.
});
like image 101
Frédéric Hamidi Avatar answered Nov 15 '22 03:11

Frédéric Hamidi


This might help:

$('li').each(function(index) {
    if(index%2)
       alert(index + ': ' + $(this).text());
});
like image 43
shakib Avatar answered Nov 15 '22 02:11

shakib


You can use :nth-child() selector.

$("selector:nth-child(2)")
like image 42
ace Avatar answered Nov 15 '22 04:11

ace