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?
JSFIDDLE
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]");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With