Can I get current row index of a table in Javascript and can we remove the row of table with current Index that we got?
-
1What is a current row? - Also, possible duplicate of Get Current rowIndex of Table in Jqueryevolutionxbox– evolutionxbox2016-06-01 16:05:51 +00:00Commented Jun 1, 2016 at 16:05
-
sorry i mean Can we get specific index of row?nara son– nara son2016-06-01 16:08:32 +00:00Commented Jun 1, 2016 at 16:08
-
Answer right in the link aboveuser6360214– user63602142016-06-01 16:08:48 +00:00Commented Jun 1, 2016 at 16:08
-
1@SuperCoolHandsomeGelBoy The link above is for jQuery, not pure JavaScript.Jake Reece– Jake Reece2019-05-02 18:30:46 +00:00Commented May 2, 2019 at 18:30
Add a comment
|
6 Answers
The rowIndex property returns the position of a row in table
function myFunction(x) {
console.log("Row index is: " + x.rowIndex);
}
<table>
<tr onclick="myFunction(this)">
<td>Click to show rowIndex</td>
</tr>
<tr onclick="myFunction(this)">
<td>Click to show rowIndex</td>
</tr>
<tr onclick="myFunction(this)">
<td>Click to show rowIndex</td>
</tr>
<tr onclick="myFunction(this)">
<td>Click to show rowIndex</td>
</tr>
</table>
2 Comments
TheHaloDeveloper
rowIndex is undefined?cskwg
rowIndex is a property of TR. So you have to find the matching TR first.
If you are using JQuery, use method .index()
var index = $('table tr').index(tr);
If no JQuery used, you can loop through all the TR element to find the matched TR.
var index = -1;
var rows = document.getElementById("yourTable").rows;
for (var i=0;i<rows.length; i++){
if ( rows[i] == YOUR_TR ){
index = i;
break;
}
}
1 Comment
nara son
but i am not using jquery.
To find the current row/column you might find this code useful. Note that I've used parentNode to get the <tr> needed for rowIndex :
var table = document.getElementById("clickTable");
for (var i = 0; i < table.rows.length; i++) {
for (var j = 0; j < table.rows[i].cells.length; j++){
table.rows[i].cells[j].onclick = function () {
r = this.parentNode.rowIndex;
c = this.cellIndex;
alert("you clicked on\n column: "+c+"\n row:"+r);
};
}
}
<table id="clickTable" border="1" cellpadding="15">
<tr><td>A1</td><td>B1</td><td>C1</td></tr>
<tr><td>A2</td><td>B2</td><td>C2</td></tr>
<tr><td>A3</td><td>B3</td><td>C3</td></tr>
</table>
Comments
By default the event object will contain the rowindex property
function myFunction() {
var x = document.getElementsByTagName("tr");
var txt = "";
var i;
for (i = 0; i < x.length; i++) {
txt = txt + "The index of Row " + (i + 1) + " is: " + x[i].rowIndex + "<br>";
}
document.getElementById("demo").innerHTML = txt;
}
<table>
<tr onclick="myFunction(this)">
<td>Click to show rowIndex</td>
</tr>
<tr onclick="myFunction(this)">
<td>Click to show rowIndex</td>
</tr>
<tr onclick="myFunction(this)">
<td>Click to show rowIndex</td>
</tr>
</table>