“ All but not”jQuery 选择器

我可以选择(使用 jQuery) HTML 标记中的所有 div,如下所示:

$('div')

但是我想从上面的选择中排除一个特定的 div(假设有 id="myid")。

如何使用 Jquery 函数实现这一点?

94539 次浏览
   var elements =  $('div').not('#myid');

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

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.

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

[doc]

or

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

[doc]

are main ways to select all but one id

You can see demo here

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

this is what you need i think.

That should do it:

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

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.

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 :(