1

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!

1252748
  • 14,597
  • 32
  • 109
  • 229

1 Answers1

5

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);
});
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Thanks for this! But what does the return do. How can I change this into an if statement? Like if it doesn't have the ancestor, then turn it red? – 1252748 Nov 27 '12 at 20:35
  • Did you see the fiddle attached? It basically is an if statement, filtering out the elements that has an ancestor with that class. To filter the other way just remove the not (!) after "return" ? – adeneo Nov 27 '12 at 20:39
  • I guess I just don't understand `return` in a sense other than returning a value from a function.. – 1252748 Nov 27 '12 at 20:40
  • It returns that css. but what if i want to do multiple things to elements fulfilling (or not fulfilling) that filter? For example if these elements I selected that don't have the ancestor of a particular class, I wanted to change those to red and change a variable `pass` to `false`..? – 1252748 Nov 27 '12 at 20:41
  • If you need the collection of elements after they are filtered you can always store them in a variable? I'll add that to my answer! As for variable, you'll need to explain that, as you can't set a variable for each element, but you could set one if elements matching some criteria exists etc ? – adeneo Nov 27 '12 at 20:45