Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining jQuery :not and :nth-child selectors

$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! :)

like image 656
Luke Carbis Avatar asked May 09 '12 05:05

Luke Carbis


People also ask

Can we use multiple selectors in jQuery?

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.

Which jQuery selector is fastest?

HTML. After seeing the result of the above code, it is crystal clear that the ID selector is the fastest.

What's the difference between the nth of type () and Nth child () selectors?

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 .

What is EQ jQuery?

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


2 Answers

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().
like image 179
David Thomas Avatar answered Oct 15 '22 22:10

David Thomas


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/

like image 45
kinakuta Avatar answered Oct 15 '22 23:10

kinakuta