Manan Sharma
Manan Sharma

Reputation: 569

How to iterate through a table row and perform a specific operation at a <td> if an element exists is true?

I have the following table here:

<table id="users-table">
 <tbody>
  <tr>
    <td class="uid">1234</td>
    <td class="user-checkbox"><input type="checkbox"></td>
  </tr>
 </tbody>
</table>

There are multiple <tr> in the <tbody>

I need to write code to check if the .uid class of <td> matches the uID variable in the code and if it does, I need to check that checkbox with the class .user-checkbox.

Upvotes: 1

Views: 80

Answers (1)

Manan Sharma
Manan Sharma

Reputation: 569

Here's a native JS code

const uID = 1234;

const rows = document.querySelectorAll("#users-table tbody tr");
rows.forEach(row => {
  const uidCell = row.querySelector(".uid");
  if (uidCell.textContent === uID.toString()) {
    const checkbox = row.querySelector(".user-checkbox input");
    checkbox.checked = true;
  }
});

Upvotes: 1

Related Questions