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

dom, javascript

Solution

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

Problem

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); } ```

Original source

Related problems