Home > Blockchain >  How to change TD on this table using JQuery
How to change TD on this table using JQuery

Time:01-27

I'm very new to JQuery and I want to ask if anyone know how to loop to this table using JQuery, get the first row id and change the fifth TD data

<table id="thisTable">
  <thead>
  </thead>
  <tbody>
    <tr id="45215">
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td>Change This TD</td>
    </tr>
    <tr></tr>
    <tr></tr>
    <tr></tr>
  </tbody>
  <tbody>
    <tr id="78955">
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td>Change This TD</td>
    </tr>
    <tr></tr>
    <tr></tr>
    <tr></tr>
  </tbody>
</table>

Thank you in advance.

I'm researching everywhere, but seem to be very confuse.

CodePudding user response:

Inside loop using $(this) and :last pseudo you can change your td text.

Or using :nth-child find td:nth-child(5) for 5th td and change your text.

Example:

$('#thisTable > tbody  > tr').each(function(index, tr) {
  // uncomment below line if you want to use nth-child
  // $(this).find('td:nth-child(5)').html("new td");
  $(this).find('td:last').html("new td");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="thisTable">
  <thead>
  </thead>
  <tbody>
    <tr id="45215">
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td>Change This TD</td>
    </tr>
    <tr></tr>
    <tr></tr>
    <tr></tr>
  </tbody>
  <tbody>
    <tr id="78955">
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td>Change This TD</td>
    </tr>
    <tr></tr>
    <tr></tr>
    <tr></tr>
  </tbody>
</table>

CodePudding user response:

Use tr:first-child to get the first <tr> and then use .find('td:nth-child(5)') to get the 5th <td> from this selected row.

$("#thisTable tr:first-child").find('td:nth-child(5)').html("NEW TD");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="thisTable">
  <thead>
  </thead>
  <tbody>
    <tr id="45215">
      <td>45215</td>
      <td></td>
      <td></td>
      <td></td>
      <td>Change This TD</td>
    </tr>
    <tr id="45216">
      <td>45215</td>
      <td></td>
      <td></td>
      <td></td>
      <td>DONT Change This TD</td>
    </tr>
    <tr></tr>
    <tr></tr>
    <tr></tr>
  </tbody>
  <tbody>
    <tr id="78955">
      <td>78955</td>
      <td></td>
      <td></td>
      <td></td>
      <td>Change This TD</td>
    </tr>
    <tr></tr>
    <tr></tr>
    <tr></tr>
  </tbody>
</table>

  • Related