Javascript “所有但不是”jQuery 选择器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7938259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:07:51  来源:igfitidea点击:

"All but not" jQuery selector

javascriptjqueryjquery-selectors

提问by siva636

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

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

$('div')

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

但我想从上述选择中排除一个特定的div(比如有id="myid")。

How can I do this using Jquery functions?

如何使用 Jquery 函数执行此操作?

回答by Bojangles

Simple:

简单的:

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

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

Using.not()将从 返回的集合中删除与给定选择器匹配的元素$('div')

You can also use the :not()selector:

您还可以使用:not()选择器:

$('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.

两个选择器都做同样的事情,但是:not()速度更快,大概是因为 jQuery 的选择器引擎 Sizzle 可以将其优化为原生.querySelectorAll()调用。

回答by Raynos

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.

你可以用老式的方式来做。不需要 jQuery 这么简单的东西。

Pro tips:

专业提示:

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

一组 dom 元素只是一个数组,因此toArrayNodeList.

Adding elements to a set is just

将元素添加到集合只是

set.push.apply(set, arrOfElements);

set.push.apply(set, arrOfElements);

Removing an element from a set is

从集合中删除元素是

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

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

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

您不能一次轻松删除多个元素:(

回答by genesis

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

[doc]

[文档]

or

或者

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

[doc]

[文档]

are main ways to select all but one id

是选择除一个 id 以外的所有 id 的主要方法

You can see demo here

你可以在这里看到演示

回答by Ehtesham

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

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

这将包括除 ID 为“myid”的所有 div

回答by abhijit

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

this is what you need i think.

我认为这就是你需要的。

回答by iappwebdev

That should do it:

那应该这样做:

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

回答by Kyle

You use the .notproperty of the jQuery library:

您使用.notjQuery 库的属性:

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

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

这里查看它的实际效果。div #myDiv 将是白色的。