Javascript Element How to - Handle click event for table row tr








Question

We would like to know how to handle click event for table row tr.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){<!--   w  w w  .j  a  v a  2 s  .c  om-->
var rows = document.getElementsByTagName("tr");
    for (var i = 0; i < rows.length; i++)
    {
        rows[i].onclick = function() {
           console.log(this);
        };
    }
}
</script>
</head>
<body>
  <table>
    <tr>
      <td>2</td>
      <td>3</td>
    </tr>
    <tr>
      <td>2</td>
      <td>3</td>
    </tr>
  </table>
</body>
</html>

The code above is rendered as follows: