"All but not" jQuery selector

JavascriptJqueryJquery Selectors

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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.

Pro tips:

A set of dom elements is just an array, so use your favourite toArray method on a NodeList.

Adding elements to a set is just

set.push.apply(set, arrOfElements);

Removing an element from a set is

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

You can't easily remove multiple elements at once :(

Solution 3 - Javascript

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

[doc]

or

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

[doc]

are main ways to select all but one id

You can see demo here

Solution 4 - Javascript

   var elements =  $('div').not('#myid');

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

Solution 5 - Javascript

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

this is what you need i think.

Solution 6 - Javascript

That should do it:

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

Solution 7 - Javascript

You use the .not property of the jQuery library:

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

See it in action here. The div #myDiv will be white.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionsiva636View Question on Stackoverflow
Solution 1 - JavascriptBojanglesView Answer on Stackoverflow
Solution 2 - JavascriptRaynosView Answer on Stackoverflow
Solution 3 - JavascriptgenesisView Answer on Stackoverflow
Solution 4 - JavascriptEhteshamView Answer on Stackoverflow
Solution 5 - JavascriptabhijitView Answer on Stackoverflow
Solution 6 - JavascriptiappwebdevView Answer on Stackoverflow
Solution 7 - JavascriptKyleView Answer on Stackoverflow