Skip to content
the poor coder

How to add click event to table row js

Poor Man
Published
Reading time
2 min read
On this page

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:

Text

<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:

Text

<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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC