Ionică Bizău
Ionică Bizău

Reputation: 113385

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

Upvotes: 3

Views: 62

Answers (4)

Harry
Harry

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");

Working Demo

EDIT: Updated based on your further clarifications.

$(".test [data-required]").each(function() {
   if (!$(this).parents('.class1').length)
       $(this).css('background-color','red');
});

Working Demo2

Upvotes: 1

Ram
Ram

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

BeNdErR
BeNdErR

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

Rory McCrossan
Rory McCrossan

Reputation: 337570

Use filter():

var $inputs = $('.test [data-required]').filter(function() {
    return $(this).closest('.class1').length == 0;
});

Upvotes: 5

Related Questions