Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get elements that are not inside of an element that has a known class

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

like image 431
Ionică Bizău Avatar asked Dec 14 '25 12:12

Ionică Bizău


1 Answers

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]");
like image 165
undefined Avatar answered Dec 17 '25 00:12

undefined



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!