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
"All but not" jQuery selector
提问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 toArray
method on a NodeList
.
一组 dom 元素只是一个数组,因此toArray
在NodeList
.
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
回答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")')