Matthew Quinlan
Matthew Quinlan

Reputation:

jQuery selector : selecting ancestor whose descendent has attribute set to value

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

Upvotes: 1

Views: 348

Answers (3)

Joshua
Joshua

Reputation: 3515

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

$(".required form")

CSS:

.required form { }

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630379

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.

Upvotes: 2

Nealv
Nealv

Reputation: 6884

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

something like this ?

Upvotes: 0

Related Questions