Click on HTML table and get row number (with Javascript, not jQuery)

scatterbrain29 picture scatterbrain29 · Mar 13, 2015 · Viewed 54.7k times · Source

I would like to know how to click on a button in an HTML table and get the row and column number returned to me: For example, with the following table:

<table>
  <tr>
    <td><input type="button" value="button"></td>
    <td><input type="button" value="button"></td>
    <td><input type="button" value="button"></td>
    </tr>
    <tr>
    <td><input type="button" value="button"></td>
    <td><input type="button" value="button"></td>
    <td><input type="button" value="button"></td>
    </tr>
    <tr>
    <td><input type="button" value="button"></td>
    <td><input type="button" value="button"></td>
    <td><input type="button" value="button"></td>
    </tr>
  </table>

How would I use JavaScript to click on the first button in the second row and have it tell me that I clicked on the first cell in the second row? Does each button need to have a unique id, or not?

Answer

Gremash picture Gremash · Mar 13, 2015

Try this:

function  getId(element) {
    alert("row" + element.parentNode.parentNode.rowIndex + 
    " - column" + element.parentNode.cellIndex);
}
<table>
  <tr>
    <td><input type="button" value="button" onclick="getId(this)"></td>
    <td><input type="button" value="button" onclick="getId(this)"></td>
    <td><input type="button" value="button" onclick="getId(this)"></td>
  </tr>
  <tr>
    <td><input type="button" value="button" onclick="getId(this)"></td>
    <td><input type="button" value="button" onclick="getId(this)"></td>
    <td><input type="button" value="button" onclick="getId(this)"></td>
  </tr>
  <tr>
    <td><input type="button" value="button" onclick="getId(this)"></td>
    <td><input type="button" value="button" onclick="getId(this)"></td>
    <td><input type="button" value="button" onclick="getId(this)"></td>
  </tr>
</table>