skip to Main Content

I have this table:

<table id="test">
<thead>
<tr><td>Main Head 1</td><td>Main Head 2</td></tr>
<tr><td>Sub Head 1</td><td>Sub Head 2</td></tr>
</thead>
<tbody>
<tr><td>Data 1</td><td>Data 2</td></tr>
<tr><td>Data 1</td><td>Data 2</td></tr>
<tr><td>Data 1</td><td>Data 2</td></tr>
</tbody>
</table>

I like to insert a new first row in the thead so it looks like:

<table>
    <thead>
    <tr><td colspan="2">HEADING</td>/tr>
    <tr><td>Main Head 1</td><td>Main Head 2</td></tr>
    <tr><td>Sub Head 1</td><td>Sub Head 2</td></tr>
    </thead>
    <tbody>
    <tr><td>Data 1</td><td>Data 2</td></tr>
    <tr><td>Data 1</td><td>Data 2</td></tr>
    <tr><td>Data 1</td><td>Data 2</td></tr>
    </tbody>
    </table>

I am using jQuery, I tried:

 var cln = $('#test').clone();
 cln.prepend('<tr><th>HEADING</th></tr>');

But it puts it in the first row of the body.

2

Answers


  1. You’re trying to insert your element above the thead, use child selector to insert inside the thead.

    $("#test > thead").prepend("<tr><td colspan='2'>Heading</td></tr>")
    table,
    td {
      border: 1px solid black;
      text-align: center
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table id="test">
      <thead>
        <tr>
          <td>Main Head 1</td>
          <td>Main Head 2</td>
        </tr>
        <tr>
          <td>Sub Head 1</td>
          <td>Sub Head 2</td>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Data 1</td>
          <td>Data 2</td>
        </tr>
        <tr>
          <td>Data 1</td>
          <td>Data 2</td>
        </tr>
        <tr>
          <td>Data 1</td>
          <td>Data 2</td>
        </tr>
      </tbody>
    </table>
    Login or Signup to reply.
  2. Using find(), find thead inside your cloned element, and use prepend whatever you want to prepend.

    Example:

    var cln = $('#test').clone();
    cln.find('thead').prepend('<tr><th>HEADING</th></tr>');
    $('#divClone').append(cln);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table id="test">
      <thead>
        <tr>
          <td>Main Head 1</td>
          <td>Main Head 2</td>
        </tr>
        <tr>
          <td>Sub Head 1</td>
          <td>Sub Head 2</td>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Data 1</td>
          <td>Data 2</td>
        </tr>
        <tr>
          <td>Data 1</td>
          <td>Data 2</td>
        </tr>
        <tr>
          <td>Data 1</td>
          <td>Data 2</td>
        </tr>
      </tbody>
    </table>
    </br>
    </br>
    <div id='divClone'></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search