views:

35

answers:

1

For chrome, firefox, and safari the following code seems to work and be able to retrieve the id of the last tr in a table.

var table = document.getElementById( tableId );
    var rowid = table.lastChild.lastChild.id;

The goal is to use each rows id to keep track of what row number it is. I am using javascript to dynamcially add and remove rows. The problem is that I need a unique identifier for each row so that rows can be removed. If say there are 4 rows and row 2 is removed, the count will be 1, 3, 4. If another row is added, it can't be 4 or there will be duplicate 4's. The correct way would be to renumber everything, (but there are many elements in each row tied to their count, thus making it near hard to re-number)

Is there a better way to be doing this? Or is there a simple fix for IE javascript?

A: 

try this:

var table = document.getElementById( tableId );
var trArr = table.getElementsByTagName('tr');
var tdArr = trArr[trArr.length - 1].getElementsByTagName('td');
var rowid = tdArr[tdArr.length - 1].id;
Tim Li
the "getElementsByTagName" method return type is Array
Tim Li
What if he was using that function to get any lastchild element from any type of tag not only <table>
Garis Suero
@Garis: Then `foo.childNodes[foo.childNodes.length-1]` but be aware that in all browsers except IE meaningless, insignificant whitespace count as a child node.
slebetman
The object returned by `getElementsByTagName` is not an `Array` but rather a `NodeList`, which is Array-like in that has a `length` property and properties whose names correspond to all the numbers from 0 up to length - 1.
Tim Down
now, jquery is very famous and easy to use.like that:var rowid = $('#tableid > tr:last-child > td:last-child').attr('id');orvar rowid = $('#tableid > tr:last-child > td:last-child').get(0).id;see http://api.jquery.com/
Tim Li
Thank you, Worked perfectly. I was looking for the row's id so I pulled back one step to just the tr and it worked great in IE, Firefox, Chrome, and Opera.
Sir.Nathan Stassen