Reputation: 7728
1) How do I find the row number/index in a HTML table? The generated table doesn't have any id for row.
eg: I have a plain HTML table generated, which has 10 rows, I am adding rows dynamically to this table.(in between existing rows)
Since I am adding new row, the existing row index will change. Now I need to to find the index of each row before adding the new row.
Upvotes: 2
Views: 22511
Reputation:
"1) How do i find the row number/index in a HTML table? The generated table dosen't have any id for row."
If you mean that you already have a row, and you need its index, don't use jQuery to get it. Table rows maintain their own index via the rowIndex
property.
$('table tr').click(function() {
alert( this.rowIndex ); // alert the index number of the clicked row.
});
Demo: http://jsfiddle.net/LsSXy/
Upvotes: 7
Reputation: 23
The jQuery site is really good for finding functions, I always find myself going back to it all the time for reference and refresh. http://docs.jquery.com/
Or you can use css selectors in jquery like so
$('table tr td:first').addClass('first-row');
Upvotes: 0
Reputation: 337627
To get the index of any element within a selector use index()
.
In your case it would be:
var rowIndex = $("#myTable TR").index();
In addition, you can use eq()
to select a specific element in a group:
var thirdRow = $("#myTable TR").eq(2) // zero based .: 2 = 3rd element.
Read more on info
Read more on eq
Upvotes: 1