2

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?

0

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.