16

I want to exclude first and second element from jquery selector. I tried this:

$('p:not(:nth-child(1),:nth-child(2))')

But this only excludes the first element... Thanks

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
simPod
  • 11,498
  • 17
  • 86
  • 139
  • This should work if your first and second child are, in fact, `p` elements. Questions like this do best when the working markup is provided. – BoltClock May 13 '12 at 22:36

5 Answers5

32

This jQuery sequence uses .slice() to discard the first two elements from the $('p') selector:

$('p').slice(2).

see http://jsfiddle.net/alnitak/zWV7Z/

Note that this is not the same as nth-child - the exclusion is based on the whole set of elements found in the first selector, and not on their relative position in the DOM.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
19

Simply:

$('p:gt(1)')

http://api.jquery.com/gt-selector/

Demo http://jsfiddle.net/NtFYq/1/

As Alnitak has pointed out in the comment, if performance is a concern, you can use his solution of slice

Thanks a lot @Alnitak for pointing that out :)

Andreas Wong
  • 59,630
  • 19
  • 106
  • 123
5
 $('p').not(":nth-child(1)").not(":nth-child(2)")

-- SEE DEMO --

Curtis
  • 101,612
  • 66
  • 270
  • 352
2

try:

$('p:not(:nth-child(1)),p:not(:nth-child(2))')

Reference: http://www.w3.org/TR/selectors/#negation

from that reference: "The negation pseudo-class, :not(X), is a functional notation taking a simple selector (excluding the negation pseudo-class itself) as an argument...."

Faust
  • 15,130
  • 9
  • 54
  • 111
  • This is relevant to CSS, but not to jQuery; jQuery's version of the `:not()` selector allows a comma-separated list of any arbitrarily complicated selector, and the only reason to write a CSS-valid version in a jQuery string is for performance (see the comments on one of the other answers about `querySelectorAll()`). I'm going to post a question detailing this difference soon... – BoltClock May 13 '12 at 22:14
  • 1
    If you really did want to write a CSS-valid version, it should be `p:not(:nth-child(1)):not(:nth-child(2))`, not `p:not(:nth-child(1)),p:not(:nth-child(2))`. Again, this will be covered in my post. – BoltClock May 13 '12 at 22:15
  • @BoltClock: I see, the selector needs to produce the negation of the union [1st, 2nd] not the union of the negation of each [1st], and [2nd], because the latter would just include all children since [1st] and [2nd] are mutually exclussive. Thanks. – Faust May 14 '12 at 07:35
  • As promised... [What's the difference in the :not() selector between jQuery and CSS?](http://stackoverflow.com/questions/10711730/whats-the-difference-in-the-not-selector-between-jquery-and-css) – BoltClock May 23 '12 at 05:54
0
$('p').not($('p').eq(0), $('p').eq(1)) 
Ram
  • 143,282
  • 16
  • 168
  • 197