views:

16

answers:

3

Struggling with CSS selector. Want to select all FORM elements that are ancestors of {elements having class='required'}. Any ideas?

A: 
$(".required").parents("form").each(function(){
    $(this) ///... do something
});

something like this ?

Nealv
A: 

You can use .closest() to get the nearest ancestor matching the selector, like this:

$(".required").closest("form")

or, alternatively you can use :has(), like this:

$("form:has(.required)")

This translates to: <form> elements that contain an element with class="required", same result (since forms can't be nested), just coming from the opposite direction.

Nick Craver
Perfect. I like the $(".required").closest("form") because in .Net I do run into nested forms (blasphemy I know). THANKS!
Matthew Quinlan
A: 

To select all ancestor form elements at any level would be:

$(".required form")

CSS:

.required form { }

Joshua
I believe that your selector would give me all FORM elements who have an ancestor whose class = 'required'. But I am looking for all FORM elements who have a descendent whose class = 'required'. I just found the has() function so I think this may work : $("form").has("form .required")
Matthew Quinlan