Javascript Reference - HTML DOM TableData cellIndex Property








The cellIndex property returns the position of a cell in the cells collection of a table row.

Browser Support

cellIndex Yes Yes Yes Yes Yes

Syntax

Return the cellIndex property.

var v = tabledataObject.cellIndex

Return Value

A Number type value representing the position of the cell in the cells collection of the table row.





Example

The following code shows how to get the index position of each cell in a table row.


<!DOCTYPE html>
<html>
<head>
<style>
table, td {<!--from w  w  w .  j  ava2s.  c  o m-->
    border: 1px solid black;
}
</style>
</head>
<body>

<table>
  <tr>
    <td>Cell 1</td>
    <td>Cell 2</td>
    <td>Cell 3</td>
    <td>Cell 4</td>
  </tr>
</table>
<button onclick="myFunction()">test</button>
<script>
function myFunction() {
    var x = document.getElementsByTagName("td");
    var i;
    for (i = 0; i < x.length; i++) {
        console.log(x[i].cellIndex);
    }
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to Click on different cells to alert their index position.


<!DOCTYPE html>
<html>
<head>
<style>
table, td {<!--  www .  ja v a  2  s  .com-->
    border: 1px solid black;
}
</style>
</head>
<body>

<p>Click on each td element to alert its position in the table row.</p>

<table>
  <tr>
    <td onclick="myFunction(this)">Click to show cellIndex</td>
    <td onclick="myFunction(this)">Click to show cellIndex</td>
    <td onclick="myFunction(this)">Click to show cellIndex</td>
    <td onclick="myFunction(this)">Click to show cellIndex</td>
  </tr>
</table>

<script>
function myFunction(x) {
    console.log("Cell index is: " + x.cellIndex);
}
</script>

</body>
</html>

The code above is rendered as follows: