$j('.select-all-these:not(.except-these):nth-child(3n)');
I'm trying to select every third item that doesn't have a particular class. This is my jQuery selector, but it doesn't work - it seems that the :nth-child selector ignores the :not selector. Am I doing it wrong?
As an example, this is how it should work:
.select-all-these.except-these
.select-all-these.except-these
.select-all-these.except-these
.select-all-these
.select-all-these.except-these
.select-all-these
.select-all-these <-- THIS ONE IS SELECTED
.select-all-these.except-these
Thanks! :)
You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.
HTML. After seeing the result of the above code, it is crystal clear that the ID selector is the fastest.
As a general rule, if you want to select an interval of a selector regardless of the type of element it is, use nth-child . However, if you want to select a specific type only and apply an interval selection from there, use nth-of-type .
jQuery eq() Method The eq() method returns an element with a specific index number of the selected elements. The index numbers start at 0, so the first element will have the index number 0 (not 1).
The only way I could see to make this work was to use two filter()
calls:
$('.select').filter(
function(){
return !$(this).hasClass('dontselect');
}).filter(
function(i){
return (i+1)%3 == 0; // unless you want a zero-based count, regular CSS is one-based
}).css('color','red');
JS Fiddle demo.
You could, though, use a single filter()
call, with an external variable:
var count = 0;
$('.select').filter(
function(){
console.log(!$(this).hasClass('dontselect'));
if (!$(this).hasClass('dontselect')){
count++;
return count%3 == 0;
}
}).css('color','red');
JS Fiddle demo.
JS Perf reports that the single filter is, unsurprisingly, a little faster, but only very, very, very marginally.
References:
filter()
.hasClass()
.How about using the method to filter the results instead?
$('.select-all-these:nth-child(3n)').not('.except-these');
Here's a fiddle to demonstrate: http://jsfiddle.net/ntNgC/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With