Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Every nth element in a jQuery set

Tags:

jquery

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?
like image 270
wingy Avatar asked Aug 19 '12 10:08

wingy


3 Answers

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;    
    });
like image 88
Darin Dimitrov Avatar answered Nov 09 '22 11:11

Darin Dimitrov


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

like image 40
nbrooks Avatar answered Nov 09 '22 12:11

nbrooks


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

like image 40
RkHirpara Avatar answered Nov 09 '22 11:11

RkHirpara