Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add a row below a specific row

I want to add a row below another but it is added at the end.

<html>
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <table style="width: 200px" border="1">
      <tr>
        <th style="width: 100px">A</th>
        <th style="width: 100px">B</th>
      </tr>
      <tr id="info">
        <td>Data1</td>
        <td>Data2</td>
      </tr>
      <tr>
        <th colspan="2">C</th>
      </tr>
    </table>
    <br />
    <button type="button" onclick="AddRow()">Add Row</button>
  </body>
</html>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  function AddRow() {
    $('#info').parent().append('<tr><td>Data3</td><td>Data4</td></tr>');
  }
</script>

I would like it to be added as follows. Is there a way to achieve this?

demo

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The parent of tr#info is the table itself. Therefore when you append() to that table the content is placed at the end.

To do what you require select #info and use after() to insert the content directly after the target:

jQuery($ => {
  $('.add-row').on('click', () => {
    $('#info').after('<tr><td>Data3</td><td>Data4</td></tr>');
  });
});
table { width: 200px; }
th { width: 100px; }
<table border="1">
  <tr>
    <th>A</th>
    <th>B</th>
  </tr>
  <tr id="info">
    <td>Data1</td>
    <td>Data2</td>
  </tr>
  <tr>
    <th colspan="2">C</th>
  </tr>
</table><br />

<button type="button" class="add-row">Add Row</button>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

Also note in the example above that I moved the inline CSS to an external stylesheet and the inline JS event handler to an unobtrusive one attached via jQuery. Your HTML should ideally contain no code other than HTML.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading