I have an onclick function attached to each <td> element. The function needs to know the placement in the table (row and column).
I found an attribute called rowIndex for <tr>s, but that would involve getting the parent element and still doesn't help with column number.
Here is my function so far (it's within a loop, so it's attaching to every td)
td.onclick = function(event) {
event = (event) ? event : window.event;
console.log('rowIndex, colIndex');
}
I could figure this out with jQuery, but I'm trying to do without.
My first thoughts were:
var rows = document.getElementsByTagName('tr');
var cells = document.getElementsByTagName('td');
var cellsPerRow = cells.length/rows.length;
var i = 0;
for (r=0;r<rows.length;r++){
for (c=0;c<cellsPerRow;c++){
cells[i].setAttribute('data-col',c + 1);
cells[i].setAttribute('data-row',r + 1);
cells[i].onclick = function(){
var row = this.getAttribute('data-row');
var col = this.getAttribute('data-col');
alert('Row: ' + row + '; col: ' + col);
};
i++;
}
}
JS Fiddle demo.
This was then refined to:
var cells = document.getElementsByTagName('td');
for (i=0;i<cells.length;i++){
cells[i].onclick = function(){
var row = this.parentNode.rowIndex + 1;
var col = this.cellIndex + 1;
alert('Row: ' + row + '; col: ' + col);
};
}
JS Fiddle demo.
element.cellIndex
will give you the column zero-indexed position.
Example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With