Reliable way to get the "ancestor" of an object with a specific classname, using jQuery

Posted by Matt Dawdy on Stack Overflow See other posts from Stack Overflow or by Matt Dawdy
Published on 2010-04-16T15:14:58Z Indexed on 2010/04/16 15:23 UTC
Read the original article Hit count: 325

Filed under:
|

I've got a javascript function that gets called on change event of a select form element. So, the "this" variable in js refers to the select element.

This select element is in a td tag, in a tr tag. The tr tag has a classname of "FilterDetailsRow".

Now, I've tested, and if I use this syntax:

var filterRow = $(this).parent().parent();

it gets me what I want. However, is there a better way to tell jQuery, "starting with "this" can you please go up my tree of parents until you find one with a classname of "FilterDetailsRow"?

Here's what I came up with, but I want to make sure I"m not reinventing the wheel.

function GetFilterDetailsRowOfObject(o) {
    if (o) {
        if (o.parent()[0].className.indexOf("FilterDetailsRow") != -1)
            return o;
        else
            return GetFilterDetailsRowOfObject(o.parent());
    } else {
        return null;
    }
}

Thanks for any advice.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery