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.
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;
I would use filter for such case,
$('li').filter(function (i, item) {
return i != 2;
})
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 + ')') );
}