wingy wingy - 4 months ago 9
jQuery Question

Every nth element in a jQuery set

I wanna select every nth in a jQuery set of elements.

Eg.


  1. How do I select every third (C and F) in

    $('<ul><li>A</li><li>B</li><li>C</li><li>D</li><li>E</li><li>F</li><li>G</li></ul>')

  2. How do I select all other elements that is not every third (A, B, D, E, G) of the same set?


Answer

You could use the $.grep function which passes to the callback the each element in the set as well as its index (0 based). So it's up to you to decide which one you want to keep:

var elements = $('<ul><li>A</li><li>B</li><li>C</li><li>D</li><li>E</li><li>F</li><li>G</li></ul>').find('li');
var result = $.grep(elements, function(element, index) {
    return (index + 1) % 3 == 0;
});

and if you wanted the other elements simply invert the condition: (index + 1) % 3 != 0

Another possibility is to use the .filter() function:

var result = $('<ul><li>A</li><li>B</li><li>C</li><li>D</li><li>E</li><li>F</li><li>G</li></ul>')
    .find('li')
    .filter(function(index) {
        return (index + 1) % 3 == 0;    
    });