wingy
wingy

Reputation: 559

Every nth element in a jQuery set

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

Eg.

<ul>
  <li>A</li>
  <li>B</li>
  <li>C</li>
  <li>D</li>
  <li>E</li>
  <li>F</li>
  <li>G</li>
</ul>
  1. How do I select every third (C and F) element?
  2. How do I select all other elements that is not every third (A, B, D, E, G) of the same set?

Upvotes: 7

Views: 9947

Answers (3)

RkHirpara
RkHirpara

Reputation: 183

I am just replying in general sense, you can say extension to your problem definition (so it can be useful to many).

Let say if you want to select every 3rd element, but start of the element not necessarily the 3rd element. If you want to have the first element as a start element means selection should be A,D,G or skip these elements follow

  1. $('li:nth-child(3n - 2)')
  2. $('li').not(':nth-child(3n- 2)')

here 3 of "3n" will select 3rd element and "- 2" bring the selection to the first element.

In generalized form

  1. $('li:nth-child(3n - x)')
  2. $('li').not(':nth-child(3n- x)')

Here x is being variable to define the first element as elaborated in the ex. above

Thanks and Regards,
Rk_Hirpara

Upvotes: 1

nbrooks
nbrooks

Reputation: 18233

Working Demo


(1) $('li:nth-child(3n)') - Select every third list-item

http://api.jquery.com/nth-child-selector/

(2) $('li').not(':nth-child(3n)') - Select others

http://api.jquery.com/not/


If you don't have the elements in the DOM, but only in the string specified in the question, combine these techniques with .children():

var thirds = $('<ul><li>A</li>...</ul>').children('li:nth-child(3n)');

var others = $('<ul><li>A</li>...</ul>').children('li').not(':nth-child(3n)');

In this case, .children() and .find() can be used interchangeably since you don't have any nested elements in the list-items; in general though, the former only searches a single level down, while the latter searches through all descendants (which is not as efficient if you know you only want to go one level down).

Upvotes: 7

Darin Dimitrov
Darin Dimitrov

Reputation: 1038890

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;    
    });

Upvotes: 11

Related Questions