views:

5138

answers:

8

Hello,

I am currently trying to find the parent of a parent of an element. I have a link being clicked that is in a <td>, and I'd like to get the <tr> object.

Why wont "$(this).parent().parent()" work? What will?

Thanks,
Brendan

Edit: It appears an error in my syntax was throwing the whole thing off. "$(this).parent().parent()" does in fact work, but I wound up going with $(this).closest('tr')" because it seems like the most efficient solution.

+2  A: 

I've definitely used $(this).parent().parent() before just fine. You could post some code for us to see if there might be another problem somewhere...

Gabriel Hurley
+10  A: 

It should work. You can also try $(this).parents(tag) , where tag is the tag you want to find.

For example:

$(this).parents("tr:first")

Will find the closest tr "up the chain".

Philippe Leybaert
A: 

Try wrapping the $(this).parent() into an jQuery object like $($(this).parent()) I often find the need to do this to make sure I have a valid jquery object. From there you should be able to get a hold of the parents parent, or using the prev() perhaps.

kristian nissen
This is completely pointless. All you're doing is wasting time by creating another jQuery object...
J-P
A: 

That should work... you might try

$(this).parents(':eq(1)');

The .parents(selector) says get all ancestors that match the selector

and the :eq(1) says find the oneth (zero-indexed, so the second) element in the list

Lathan
You might try alerting this, to make sure it is an html anchor tag.Try doing: alert('anchor html(' + $(this).html() + ')');
Lathan
+24  A: 

The best way would probably be using closest:

$(this).closest('tr');

Check out the documentation:

Closest works by first looking at the current element to see if it matches the specified expression, if so it just returns the element itself. If it doesn't match then it will continue to traverse up the document, parent by parent, until an element is found that matches the specified expression. If no matching element is found then none will be returned.

Paolo Bergantino
A: 

Which one is faster:

$(this).parents(':eq(1)').find('li').removeClass();

or

$(this).parent().parent().find('li').removeClass();

or

$(this).closest('ul').find('li').removeClass();

Thanks! :-)

dHahn
A: 

also try $(this).closest('div.classname').hide();

Dilip
A: 
var getParentNode = function(elem, level) { 
    level = level || 1; 
    for (var i = 0; i < level; i++) {
        if (elem != null) {
            elem = elem.parentNode; 
        }
    }
    return elem; 
}
Alex Polo