tags:

views:

258

answers:

3

I have a link ( anchor ) tag in a table cell on every row of an html table. On click of this anchor tag I want to use jquery ( preferably) to traverse back to the parent td and tr and get object reference to it.

how can i use jquery at best here to navigate\traverse in dom.

I can do a method like this but not sure if jquery has better ways for this.

function findRowNumber(element) 
{ 
  // element is a descendent of a tr element

  while(element.tagName.toLowerCase() != "tr") 
  {
   element = element.parentNode; // breaks if no "tr" in path to root
  }

  return element.rowIndex;
}
+1  A: 

In the click() function for the anchor, just use these:

$(this).parents('td:first')
$(this).parents('tr:first')
Daniel Roseman
+3  A: 

This is exactly what "closest" is for.

$(this).closest('td');
$(this).closest('tr');
MrKurt
I am new to jQuery :)Work like a breeze! thanks.
dotnetcoder
+1  A: 

.closest is neat, but was recently introduced (jQuery 1.3 or newer). If you are bound to an older version of JQuery, follow the other answer.

Franz