How to make a table row clickable with JavaScript?

Sometimes, we want to make a table row clickable with JavaScript.

In this article, we’ll look at how to make a table row clickable with JavaScript.

How to make a table row clickable with JavaScript?

To make a table row clickable with JavaScript, we can use jQuery.

For instance, we write:

<table>
  <tbody>
    <tr>
      <td><a href="#">Column 1</a></td>
      <td><a href="#">Column 2</a></td>
      <td><a href="#">Column 3</a></td>
    </tr>
  </tbody>
</table>

to add a table.

Then we write:

.highlightRow {
  background-color: green
}

to set background color for the highlightRow class.

Next, we write:

$('tr').click(function() {
  $(this).toggleClass('highlightRow');
});

to add an event handler for tr element clicks.

When we click on them, we call the toggleClass method on the tr element to toggle the highlightRow class.

Conclusion

To make a table row clickable with JavaScript, we can use jQuery.