Javascript Onclick with Table Rows


To add an onclick event to table rows in JavaScript, you can use the addEventListener method to attach an event listener to each row in the table. Here’s an example:

<table id="myTable">
      <td>John Smith</td>
      <td>[email protected]</td>
      <td>Jane Doe</td>
      <td>[email protected]</td>

  var table = document.getElementById('myTable');
  var rows = table.getElementsByTagName('tr');

  for (var i = 0; i < rows.length; i++) {
    rows[i].addEventListener('click', function() {
      // Do something when a row is clicked
      console.log('Row clicked: ' + this.cells[0].textContent);

In this example, we first get a reference to the table using getElementById. We then get all the rows in the table using getElementsByTagName(‘tr’). We iterate through each row using a for loop and attach an onclick event listener to each row using addEventListener.

When a row is clicked, the event listener function is called and the this keyword refers to the clicked row. In this example, we simply log the text content of the first cell in the row to the console.

You can modify the event listener function to perform any action you want when a row is clicked, such as highlighting the row or displaying additional information.