Categories
JavaScript Answers

How to Add an Click Event Handler to a Table Row with JavaScript?

Spread the love

Sometimes, we want to add an click event handler to a table row with JavaScript.

In this article, we’ll look at how to add an click event handler to a table row with JavaScript.

Add an Click Event Handler to a Table Row with JavaScript

To add an click event handler to a table row with JavaScript, we can loop through each row and set the onclick property of each row to an event handler.

For instance, we add a table by writing:

<table>
  <tbody>
    <tr>
      <td>foo</td>
      <td>bar</td>
    </tr>
    <tr>
      <td>baz</td>
      <td>qux</td>
    </tr>
  </tbody>
</table>

Then we write:

const createClickHandler = (row) => {
  return () => {
    const [cell] = row.getElementsByTagName("td");
    const id = cell.innerHTML;
    console.log(id);
  };
};

const table = document.querySelector("table");
for (const currentRow of table.rows) {
  currentRow.onclick = createClickHandler(currentRow);
}

to add event handlers toe each row.

We define the createClickHandler function that takes the table row as a parameter.

And we get the first td in the row with getElementsByTagName and destructuring.

Then we get the cell‘s innerHTML property and log that in the handler.

Next, we select the table element with document.querySelector.

And then we use the for-of loop to loop through each table row which we get with table.rows.

And then we assign the onClick property of each row to the event handler created by createClickHandler.

Conclusion

To add an click event handler to a table row with JavaScript, we can loop through each row and set the onclick property of each row to an event handler.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *