All but Not jQuery Selector

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

$('div') 

But I want to exclude a specific div (for example, having id="myid" ) from the above selection.

How to do this using jQuery functions?

+67
javascript jquery jquery-selectors
Oct 29 '11 at 10:21
source share
7 answers

Plain:

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

Using .not() will remove the elements corresponding to the selector selected by 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() faster , presumably because the jQuery Sizzle selector mechanism can optimize it in a native .querySelectorAll() call.

+126
Oct 29 '11 at 10:23
source share
 var els = toArray(document.getElementsByTagName("div")); els.splice(els.indexOf(document.getElementById("someId"), 1); 

You could just do it the old fashioned way. No need for jQuery with something so simple.

Professional Tips:

The dom element set is just an array, so use your favorite toArray method on a NodeList .

Adding items to a set is easy

set.push.apply(set, arrOfElements);

Removing an item from a collection

set.splice(set.indexOf(el), 1)

You cannot easily delete several items at once :(

+9
Oct 29 '11 at 10:33
source share
 $("div:not(#myid)") 

[doc]

or

 $("div").not("#myid") 

[doc]

- basic ways to select all but one id

Here you can see the demo.

+5
Oct 29 '11 at 10:24
source share
  var elements = $('div').not('#myid'); 

This will include all divs except one with id 'myid'

+4
Oct 29 '11 at 10:23
source share
 $('div:not(#myid)'); 

that’s what you need, I think.

+3
Oct 29 '11 at 10:24
source share

This should do it:

 $('div:not("#myid")') 
+3
Oct 29 '11 at 10:25
source share

You use the .not property of the .not library:

 $('div').not('#myDiv').css('background-color', '#000000'); 

See in action here . Div #myDiv will be white.

+3
Oct 29 '11 at 10:27
source share



All Articles