Get first matching ancestor containing a specific class
Asked Answered
S

2

19

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.

Statist answered 28/7, 2011 at 15:37 Comment(4)
or beter create a jsfiddle.netPepillo
I am new to this and each toime I post markup it becomes part of the page.Statist
The closest example should be the correct way to do this. As Shankar says, we need to see your HTML code.Object
@Statist Select the code you want to show and press the icon with the two curly brackets {} above the text box. This will format the content as code.Object
N
24

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");
Nubianubian answered 28/7, 2011 at 15:43 Comment(3)
still testing. Will get back.Statist
Thank you to everyone who responded.Statist
Silly name for a function, it should be named ancestor, firstAncester or closestAncester. There's nothing in its name to indicate the DOM traversal is in the up direction.Igenia
H
3

Try this:

$("#txtMyBox2").parents(".sys-form-row:first");
Hive answered 28/7, 2011 at 15:44 Comment(1)
In my case closest was also giving 2 elemments, this works perfectlyIscariot

© 2022 - 2024 — McMap. All rights reserved.