1

I am trying to insert a new row before the last (n-th) row in a table. However, Using the code below it instead nests the new

<tr></tr> inside the n-th <tr></tr>. Making the output look like this:

<tr><tr></tr></tr>

This is the code:

$('#sbdrp_table > tbody tr:last-child')
  .append('<tr><td>my data</td><td>more data</td></tr>');

This is the outcome:

<tr><td colspan="2"><input style="width: 100%" type="button" class="add-row x" value="+ Add"></td>
  <tr><td>my data</td><td>more data</td></tr>
</tr>

Expected Outcome The new row should come before the last row.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
meks285
  • 29
  • 5
  • Append to the tbody `$('#sbdrp_table > tbody').append` – mplungjan Jul 08 '23 at 05:39
  • @mplungjan This will add the row after the last which happens to be the "Add new row" button. Expected Outcome should be before the last row – meks285 Jul 08 '23 at 05:42
  • @mplungjan If I use " $('#sbdrp_table > tbody:last-child').prepend(row);" The new row is added at the beginning of which works fine for me. Im concerned that the correct code is nesting into an existing instead of creating an entirely new – meks285 Jul 08 '23 at 05:44
  • So use jQuery.before since lastChild is the last row and you append to the row, not the tbody – mplungjan Jul 08 '23 at 05:45
  • 1
    @mplungjan Thank you! This worked for me: $('#sbdrp_table > tbody tr:last').before(row); – meks285 Jul 08 '23 at 05:54
  • [dupe](https://stackoverflow.com/questions/8523860/jquery-add-row-before-fourth-to-last-row) – mplungjan Jul 08 '23 at 06:35
  • Does this answer your question? [jQuery add row before fourth to last row](https://stackoverflow.com/questions/8523860/jquery-add-row-before-fourth-to-last-row) – Alexander Nenashev Jul 08 '23 at 11:01
  • @AlexanderNenashev Probably. II used this: $('#sbdrp_table > tbody tr:last').before(row); So I guess that should work also. – meks285 Jul 10 '23 at 08:45

0 Answers0