Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traversing table and returning clicked element's placement

Tags:

javascript

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.

like image 691
Matthew Avatar asked Jan 29 '26 05:01

Matthew


2 Answers

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.

like image 132
David Thomas Avatar answered Jan 30 '26 20:01

David Thomas


element.cellIndex

will give you the column zero-indexed position.

Example

like image 32
Joe Avatar answered Jan 30 '26 18:01

Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!