views:

28

answers:

2

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.

+4  A: 

You can use closest to find the first matching ancestor:

var filterRow = $(this).closest('.FilterDetailsRow');
LukeH
+1  A: 

In jQuery 1.4 you can use parentsUntil. For you it would be something like

$(this).parentsUntil('.FilterDetailsRow');
rosscj2533
Not what the question is asking for. From the `parentsUntil` documentation: "Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector."
LukeH
closest() is best for this. Though, it starts with the current element (unlike parents() which starts with the first element), it will return zero or one object.
tb
@Luke, ah, you're right. To use this you'd have to go up one more level and then select the right parent out of the jQuery object returned. Your answer works much more nicely.
rosscj2533
So, are you saying to use this (I'll use Luke's answer, but just asking so I understand) I would probably want $(this).parentsUntil('.FilterDetailsRow').parent(); ?
Matt Dawdy
@Matt, yes that is correct. I thought it may be more complicated since parentsUntil returns all ancestors between your `this` and the selector passed to it, but after a quick test the code you proposed does work as expected.
rosscj2533