Reputation: 559
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>
Upvotes: 7
Views: 9947
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
$('li:nth-child(3n - 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
$('li:nth-child(3n - x)')
$('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
Reputation: 18233
(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
.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
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