Reputation: 113385
Suppose you have the following HTML code:
<div class="test">
<div class="class1">
<input type="text" data-required="true"/>
</div>
<input type="text" data-required="true"/>
</div>
I want to get all elements that have data-required
attribute from .test
that are not inside of the .class1
div.
So, in the example above only the second input would be returned.
I tried:
$(".test [data-required]:not('.class1')")
but it returns the both input because :not
doesn't select the parent elements.
Is this possible with one jQuery selector?
Upvotes: 3
Views: 62
Reputation: 89750
You can use the below. It selects only the direct children of .test
.
Note: Wouldn't include elements with data-required
under say .class2
also.
$(".test > [data-required]").css("background", "red");
EDIT: Updated based on your further clarifications.
$(".test [data-required]").each(function() {
if (!$(this).parents('.class1').length)
$(this).css('background-color','red');
});
Upvotes: 1
Reputation: 144689
One way of doing this:
$(".test [data-required]").filter(function() {
return !$(this).closest('.class1').length;
}).css("background", "red");
.filter()
method is much faster than spaghetti-like selectors, if you don't want to use .filter()
, probably you can use this long, inefficient selector:
$(".test > [data-required], .test :not(.class1) [data-required]");
Upvotes: 6
Reputation: 17927
If the input you want to find is always a direct child of .test
div, you can use
$(".test > [data-required]").css("background", "red");
FIDDLE http://jsfiddle.net/wERTv/1/
Upvotes: 1
Reputation: 337570
Use filter()
:
var $inputs = $('.test [data-required]').filter(function() {
return $(this).closest('.class1').length == 0;
});
Upvotes: 5