Reputation: 28503
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
?
Upvotes: 1
Views: 567
Reputation: 38345
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.
Upvotes: 1
Reputation: 388316
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
Upvotes: 2
Reputation: 74738
May be with a >
direct child notation:
$('#foo > a')
You can omit some elem with .not()
:
$("#foo a").not('#bar a').length;
Upvotes: 1
Reputation: 94469
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/
Upvotes: 3
Reputation: 8583
You can use child selectors for accomplishing your first task (getting all <a>
elements from foo
):
$('#foo > a'). ...
Upvotes: 0
Reputation: 15104
You can do that (assuming the variable foo
is your #foo
)
var a = foo.find('> a');
Upvotes: 0