user831839
user831839

Reputation: 247

Get first matching ancestor containing a specific class

I am trying to iterate to the first ancestor containing the class ‘sys-form-row’.

I am able to get the row containing class="sys-form-row" using the following: objBack =

$('#txtMyBox2').parent().parent();

This seems incredibly clumsy. What I would like to do is something like this:

$('#txtMyBox2').parents('.sys-form-row'); or even $('#txtMyBox2').closest('.sys-form-row'); however both fail and my current approach will not always work if additional div nesting is applied. Any help would be really appreciated.

Upvotes: 19

Views: 9503

Answers (2)

ShankarSangoli
ShankarSangoli

Reputation: 69905

If the additional nested div has any specific class you can use closest to find the parent

//It will always give you the closest element having class ".sys-form-row"
$('#txtMyBox2').closest(".sys-form-row");

Upvotes: 24

John Kalberer
John Kalberer

Reputation: 5790

Try this:

$("#txtMyBox2").parents(".sys-form-row:first");

Upvotes: 3

Related Questions