I have an element like so:
<div id="foo">
<a href="#" class="some">click me</a>
<div id="bar">
<a href="#" class="some">click me too</a>
</div>
</div>
and I need to select the a
elements that are not inside bar
. Problem is I can't use children()
, because my foo
is much more complex than above.
Question:
Is there a way to select "some" elements from a foo
and explicitly excluding "some" elements from bar
?
If the anchor elements may not always be a direct child of foo
you can use the filter()
method.
var anchors = $("#foo a").filter(function(){
return !$("#bar").find(this).length;
});
Working Example http://jsfiddle.net/v63tC/
You can use .filter() along with $.contains() to solve this
var $bar = $('#bar');
var items = $('#foo a.some').filter(function() {
return !$.contains($bar[0], this)
})
Demo: Fiddle
May be with a >
direct child notation:
$('#foo > a')
You can omit some elem with .not()
:
$("#foo a").not('#bar a').length;
Since you mentioned that your #foo
element is considerably more complex than the example, is it safe to assume that it's not just direct descendants that you'll need to be selecting? If that is the case, I'd suggest the following:
$('#foo a.some').filter(function() {
return $(this).parents('#bar').length === 0;
});
That selects all <a>
elements inside of #foo
, then filters them down so that only those that don't have an ancestor with the id
of bar
on them are kept.
您可以这样做(假设变量foo
是您的#foo
)
var a = foo.find('> a');
您可以使用子选择器来完成第一个任务(从foo
获取所有<a>
元素):
$('#foo > a'). ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.