fightstarr20
fightstarr20

Reputation: 12598

jQuery append new row to table - detecting existing rows but not adding new

I have a basic HTMl table like this...

jQuery(document).ready(function() {
  /* Calculate Total */
  jQuery('table tr.customRow').each(function(i, row) {
    console.log('Found Row');
    jQuery(this).append('<tr>New Test Row</tr>');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr class="customRow">
    <td>
      My Row 1
    </td>
  </tr>
  <tr class="customRow">
    <td>
      My Row 2
    </td>
  </tr>
  <tr class="customRow">
    <td>
      My Row 3
    </td>
  </tr>
</table>

I am trying to use jQuery to add a new <tr> above each found <tr> using append. The console log shows that it is finding the rows but is not adding the new one.

Where am I going wrong?

Upvotes: 2

Views: 42

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

There's two issues in your code. Firstly the HTML you're trying to add is invalid. <tr> elements cannot contain text nodes. You need to wrap the content in a td or th.

Secondly append() will be placing the new tr inside the existing tr, which again is invalid HTML. Given your goal use before() instead.

Also note that, because the new content is the same in all cases, an each() loop is not required here. jQuery will implicitly loop over the collection and create the content on every selected element for you. Try this:

jQuery(function($) {
  $('table tr.customRow').before('<tr><td>New Test Row</td></tr>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr class="customRow">
    <td>My Row 1</td>
  </tr>
  <tr class="customRow">
    <td>My Row 2</td>
  </tr>
  <tr class="customRow">
    <td>My Row 3</td>
  </tr>
</table>

Upvotes: 2

Mitya
Mitya

Reputation: 34556

You're not trying to add new trs before existing trs; you're trying to insert them INTO them.

Instead of:

jQuery(this).append('<tr>New Test Row</tr>');

You want:

jQuery(this).before('<tr>New Test Row</tr>');

Furthermore, as @Rory McCrossan points out, you can't have text nodes directly inside tr nodes - you need a td container.

Upvotes: 3

Related Questions