frrlod
frrlod

Reputation: 6685

Finding the location of a TD in a table

So let's say I have a table, and I want to manipulate a specific <td> in it:

HTML:

<table>
    <tr><td>1</td> <td>2</td></tr>
    <tr><td>3</td> <td>4</td></tr>
    <tr><td id="hi">5</td> <td>6</td></tr>
</table>

Javascript:

document.getElementsByTagName("table")[0].rows[2].cells[0];

This will help me REACH a specific cell in a table.


My question is this:

Say I have a specific <td> inside a table:

var td = document.getElementById("hi")

I want to KNOW its location in the table, so I can be able to reach it using table.rows[x].cells[y] How can I check this location?

Upvotes: 4

Views: 2260

Answers (5)

micnic
micnic

Reputation: 11255

You will need something like this:

function getRowCellPosition(table, cell) {
    for (var i = 0; i < table.rows.length; i++) {
        for (var j = 0; j < table.rows[i].cells.length; j++) {
            if (table.rows[i].cells[j] === cell) {
                return {
                    row: i,
                    cell: j
                };
            }
        }
    }
    return null;
}

or more simple:

function getRowCellPosition(cell) {
    return {
        row: cell.parentNode.rowIndex,
        cell: cell.cellIndex
    }
}

Upvotes: 2

TwiN
TwiN

Reputation: 1911

The cellIndex property of a td element gives the index of the cell in the row.
The rowIndex property of a tr element gives the index of the row in the table.

So,

var td = document.getElementById("hi");
var x = td.cellIndex;
var y = td.parentNode.rowIndex;

Upvotes: 4

neo
neo

Reputation: 801

Try this:

for row:

Array.slice(el.parentNode.parentNode.children).indexOf(el.parentNode)

for col:

Array.slice(el.parentNode.children).indexOf(el)

The slice magick is because el.parentNode.children is not an array.

edit: I wasn't aware of td.cellIndex and tr.rowIndex. Definitely use them.

Upvotes: 0

David Thomas
David Thomas

Reputation: 253416

I'd suggest, as you imply you know which specific cell you want to find, though currently untested:

var td = document.getElementById("hi"),
    col = td.cellIndex,
    row = td.parentNode.rowIndex;

Upvotes: 10

Jani Hartikainen
Jani Hartikainen

Reputation: 43253

Simply create a for loop that goes through each row and column and compare the TD in that index against the one you want.

Upvotes: 0

Related Questions