"All but not" jQuery selector

siva636 picture siva636 · Oct 29, 2011 · Viewed 86.3k times · Source

I can select (using jQuery) all the divs in a HTML markup as follows:

$('div')

But I want to exclude a particular div (say having id="myid") from the above selection.

How can I do this using Jquery functions?

Answer

Bojangles picture Bojangles · Oct 29, 2011

Simple:

$('div').not('#myid');

Using .not() will remove elements matched by the selector given to it from the set returned by $('div').

You can also use the :not() selector:

$('div:not(#myid)');

Both selectors do the same thing, however :not() is faster, presumably because jQuery's selector engine Sizzle can optimise it into a native .querySelectorAll() call.