Ok another dumb jQuery question…
The not selector in jQuery is giving me problems. I’m trying to select all but the first element having a given class toggle-button. But I can have this dialogue with the console…
? $('.toggle-button').length
4
? $('.toggle-button:not(:eq(0))').length
4
No difference. But…
? $('div').length
23
? $('div:not(:eq(0))').length
22
What gives, Resig?
Why does the not selector have different behaviour when applied to a class (seemingly) – and how can I do the select I want in the most idiomatic jQuery way?
:not(:first) does the same thing…
UPDATE
Thanks for all responses. This looks to be a bug in the jQuery/IE partnership.
Solutions…
$('.toggle-button').filter(':gt(0)')
$('.toggle-button').not(':first')
$('.toggle-button').slice(0);
…and no doubt many more. I’ll leave it to the crazies to figure which is best 😀
Any non-CSS filtering/selecting should be done through jQuery methods, as it means that jQuery is unable to use CSS to speed up the selector. It tries to use the native CSS support in the browser but if you use
:notor:eqetc, it has to use its own parsing system which is slower.The air-quotes “correct” way is this:
As to why the
:notbehaves differently, I’m not sure. I’ll keep thinking, and if I get a lightbulb, I’ll update this answer 🙂Edit: It looks like its some browser-specific quirk – I’ve just done
$('.prettyprint').length– 3$('.prettyprint:not(:eq(0))').length– 2$('.question-header').length– 1$('.question-header:not(:eq(0))').length– 0For this page, at the time I did them, those numbers were right and predictable. Double check your code for silly typos, and that kind of thing, because it looks to be working OK here.
Edit Edit: It’s an IE8 bug, presumably to do with the CSS selection engine it uses. See http://jsfiddle.net/5gSxP/2/ for a rundown of the 3 selection methods, the first one fails in IE8 but the one in this answer works OK.