Mark Tomlin
Mark Tomlin

Reputation: 8923

How to find row and col number of a cell in table

Not using jQuery, what is the most efficient way of getting the Row and Col (X, Y) of a onClick even within a table?

I would think that assigning a click listener to just the table, and let it bubble to the top would work well, but really it just gives me the HTMLTableElement. What I want to get from it is the Col number, and Row number from this one listener. Is that possible?

window.onload = function () {
 document.getElementsByTagName('table')[0].addEventListener('click', function() {
  alert(this.tagName);
 }, false);
}

Upvotes: 11

Views: 37436

Answers (3)

Jazzzzzz
Jazzzzzz

Reputation: 1633

Here is the most simple way to do that.

window.onload = function () {
  document.querySelector('#myTable').onclick = function(ev) {
    var rowIndex = ev.target.parentElement.rowIndex;
    var cellIndex = ev.target.cellIndex;
    alert('Row = ' + rowIndex + ', Column = ' + cellIndex);
  }
}
<table border="1" id="myTable">
    <tr>
        <td>first row first column</td>
        <td>first row second column</td>
    </tr>
    <tr>
        <td>second row first column</td>
        <td>second row second column</td>
    </tr>
    <tr>
        <td>third row first column</td>
        <td>third row second column</td>
    </tr>
</table>

Upvotes: 9

Sampson
Sampson

Reputation: 268344

You could bind to the table, but that would leave open the possibility that you might click within the spacing between cells (which doesn't have a row or cell index). I have decided in the example below that I would bind to the cells themselves, and thus ensure I would always have a row and cell index.

var tbl = document.getElementsByTagName("table")[0];
var cls = tbl.getElementsByTagName("td");

function alertRowCell(e){
  var cell = e.target || window.event.srcElement;
  alert( cell.cellIndex + ' : ' + cell.parentNode.rowIndex );
}

for ( var i = 0; i < cls.length; i++ ) {
  if ( cls[i].addEventListener ) {
    cls[i].addEventListener("click", alertRowCell, false);
  } else if ( cls[i].attachEvent ) {
    cls[i].attachEvent("onclick", alertRowCell);
  }
}

Demo: http://jsbin.com/isedel/2/edit#javascript,html

I suppose you could safely bind to the table itself too, and perform a check against the source element to see if it was a cell or not:

var tbl = document.getElementsByTagName("table")[0];

function alertRowCell (e) {
  var cell = e.target || window.event.srcElement;
  if ( cell.cellIndex >= 0 )
    alert( cell.cellIndex + ' : ' + cell.parentNode.rowIndex );
}

if ( tbl.addEventListener ) {
  tbl.addEventListener("click", alertRowCell, false);
} else if ( tbl.attachEvent ) {
  tbl.attachEvent("onclick", alertRowCell);
}

Demo: http://jsbin.com/isedel/5/edit

Upvotes: 20

Musa
Musa

Reputation: 97672

window.onload = function () {
 document.getElementsByTagName('table')[0].addEventListener('click', function(e) {
  alert(e.target);
 }, false);
}

Upvotes: 1

Related Questions