How to add click event to table row js

How to add click event to table row js

If you want to add a click event to a table row using JavaScript, there are a few different ways you can go about it. Here are a couple of options:

Option 1: Using onclick attribute

The simplest way to add a click event to a table row is to use the onclick attribute on the row itself. Here's an example:


<table>
  <tbody>
    <tr onclick="alert('You clicked me!')">
      <td>Row 1, Column 1</td>
      <td>Row 1, Column 2</td>
    </tr>
    <tr onclick="alert('You clicked me too!')">
      <td>Row 2, Column 1</td>
      <td>Row 2, Column 2</td>
    </tr>
  </tbody>
</table>

In this example, each table row has an onclick attribute that triggers an alert when the row is clicked. You can replace the alert with any JavaScript code you like.

Option 2: Using addEventListener method

If you prefer to keep your JavaScript separate from your HTML, you can use the addEventListener method to attach a click event to each table row. Here's an example:


<table id="myTable">
  <tbody>
    <tr>
      <td>Row 1, Column 1</td>
      <td>Row 1, Column 2</td>
    </tr>
    <tr>
      <td>Row 2, Column 1</td>
      <td>Row 2, Column 2</td>
    </tr>
  </tbody>
</table>

<script>
  var table = document.getElementById("myTable");
  var rows = table.getElementsByTagName("tr");
  
  for (var i = 0; i < rows.length; i++) {
    rows[i].addEventListener("click", function() {
      alert("You clicked me!");
    });
  }
</script>

In this example, we first get a reference to the table element and all its rows. Then we loop through the rows and add a click event listener to each one that triggers an alert when clicked.

These are just a couple of examples of how you can add click events to table rows using JavaScript. There are many other ways to achieve the same result, so feel free to experiment and find the method that works best for your project.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe