40

Does anyone know if there exist some kind of selector to select al the elements from a matched set but the one given by the indicated index. E.g.:

$("li").neq(2).size();

Supposing that there were 5 elements, the last statement would give you 4, and would contain all the <li> elements but the second one in the DOM.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
manutenfruits
  • 1,447
  • 3
  • 17
  • 25

5 Answers5

77

Use not:

$('li').not(':eq(2)');
Zbigniew
  • 27,184
  • 6
  • 59
  • 66
  • if you want the fastest neq use a filter see http://jsperf.com/jquery-fastest-neq-filter – mike Jan 02 '16 at 08:17
10

Alright, it's just

$("li:not(:eq(2))");
manutenfruits
  • 1,447
  • 3
  • 17
  • 25
7

The other answers will work just fine, but as an alternative you could implement you own custom selector for neq

$.extend($.expr[":"], {  
    neq: function(elem, i, match) {  
        return i !== (match[3] - 0);
    }  
});  

And then you could do what you originally suggested.

$("li:neq(2)").size();

Although another post suggested using .length instead of .size, which will be better as its just a property and not an extra function call.

$("li:neq(2)").length;
James Wiseman
  • 29,946
  • 17
  • 95
  • 158
  • 1
    Watch the syntax, it has changed in 1.8 http://stackoverflow.com/questions/11624345/getting-the-match-object-in-a-custom-filter-selector-in-jquery-1-8 – Kevin B Aug 21 '12 at 14:45
  • 1
    Also, doesn't this create a pseudo selector, not a method? `$("li:neq(2)")` – Kevin B Aug 21 '12 at 14:48
6

I would use filter for such case,

$('li').filter(function (i, item) {
   return i != 2;
})
Simon
  • 7,182
  • 2
  • 26
  • 42
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
1

In addition to the custom selector, you could also implement this as a jQuery plugin:

$.fn.neg = function (index) {
    return this.pushStack( this.not(':eq(' + index + ')') );
}
Eli
  • 17,397
  • 4
  • 36
  • 49