Struggling with CSS selector. Want to select all FORM elements that are ancestors of {elements having class='required'}. Any ideas?
views:
16answers:
3
A:
$(".required").parents("form").each(function(){
$(this) ///... do something
});
something like this ?
Nealv
2010-08-07 23:34:28
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
2010-08-07 23:35:10
Perfect. I like the $(".required").closest("form") because in .Net I do run into nested forms (blasphemy I know). THANKS!
Matthew Quinlan
2010-08-07 23:50:16
A:
To select all ancestor form elements at any level would be:
$(".required form")
CSS:
.required form { }
Joshua
2010-08-07 23:35:48
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
2010-08-07 23:47:49