1252748
1252748

Reputation: 15372

select div with class unless it has ancestor of another class

Asked this question ten minutes ago, but realized that I used the term parent instead of ancestor. I'm looking for something that refers to a class that has a particular ancestor.

How can I select all inputs that do not have an parent of a particular class?

Here I just want to get the inputs that do not have a parent with the class not-parent

$(document).ready(function() {

    $("div:not(.not-ancestor) > input[type='text']").css('color', '#FF1200');
});​

http://jsfiddle.net/MFtv3/3/

Thanks!

Upvotes: 1

Views: 371

Answers (1)

adeneo
adeneo

Reputation: 318222

You can use a filter and check if the element has a parent somewhere above it with the class you're looking for by using closest(), like this :

$("div > input[type='text']").filter(function() {
    return !$(this).closest('.not-ancestor').length;
}).css('color', '#FF1200');

FIDDLE

EDIT

To get the collection of elements for further use:

var elems = $("div > input[type='text']").filter(function() {
                return !$(this).closest('.not-ancestor').length;
            });

elems.css('color', 'red');
elems.each(function(idx, elem) {
    $(elem).data('index', idx);
});

Upvotes: 5

Related Questions