Devansh Pandey
Devansh Pandey

Reputation: 1

Returning Row Index from JavaScript function ,returns undefined

    function getRowIndex() {
    var tble = document.getElementById("myTable");
    for (var i = 0; i < tble.rows.length; i++) {
        for (var j = 0; j < tble.rows[i].cells.length; j++) {
            tble.rows[i].cells[j].onclick = function() {

                return this.parentElement.rowIndex;
            }
        }
    }
}
var rIndex = getRowIndex();
console.log(rIndex);

This function getRowIndex() is returning undefined when I try to print index. I want to extract the row index value in value when clicked, using javaScript.

Upvotes: 0

Views: 1139

Answers (1)

Sachin Singh
Sachin Singh

Reputation: 948

I am assuming that you are using HTML table element. You can find row index like this:

document.getElementById('myTable').addEventListener('click', (e) => {
  if (e.target.nodeName === 'TD') {
    alert(e.target.parentNode.rowIndex);
  }
});
table {
  border-collapse: collapse;
}

td {
  border: 1px solid;
  padding: 10px;
  cursor: pointer;
}
<table id="myTable">
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
  </tr>
  <tr>
    <td>4</td>
    <td>5</td>
    <td>6</td>
  </tr>
</table>

I am using event delegation here. Instead of iterating over each child element and then bind the event. I am binding the event to parent node itself and then find the click target using event.target. This has great performance benefits as you can already see.

Upvotes: 1

Related Questions