Establishment <thead> for multiple tables</thead>



  • There's a violin for the construction of thead versatile inside the table without that current.

    var thead = $("#myid tr:first").html();
    $("#myid tr:first").remove();
    $("#myid").prepend('<thead>' + thead + '</thead>');
    

    However, there are several tables on the page with different ids and one class. Could the code be minimised to avoid the need to duplicate it for each table separately. Example of what is now:

    var thead = $('#myid1 tr:first').html();
    var thead2 = $('#myid2 tr:first').html();
    

    $('#myid1 tr:first').remove();
    $('#myid2 tr:first').remove();

    $('#myid1').prepend('<thead>' + thead + '</thead>');
    $('#myid2').prepend('<thead>' + thead2 + '</thead>');

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table class="myclass" id="myid1">
    <tbody>
    <tr>
    <th>Name 1</th>
    <th>Name 2</th>
    <th>Name 3</th>
    <th>Name 4</th>
    </tr>
    <tr>
    <td>Val</td>
    <td>Val</td>
    <td>Val</td>
    <td>Val</td>
    </tr>
    <tr>
    <td>Val</td>
    <td>Val</td>
    <td>Val</td>
    <td>Val</td>
    </tr>
    </tbody>
    </table>

    <table class="myclass" id="myid2">
    <tbody>
    <tr>
    <th>Name 1</th>
    <th>Name 2</th>
    <th>Name 3</th>
    <th>Name 4</th>
    </tr>
    <tr>
    <td>Val</td>
    <td>Val</td>
    <td>Val</td>
    <td>Val</td>
    </tr>
    <tr>
    <td>Val</td>
    <td>Val</td>
    <td>Val</td>
    <td>Val</td>
    </tr>
    </tbody>
    </table>

    I'll be grateful for any help.



  • The banal cycle can be used at least.

    $('table.myclass').each(function(){
        var first = $(this).find("tr:first"), thead = first.html();
        first.remove();
        $(this).prepend('<thead>' + thead + '</thead>');  
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table class="myclass" id="myid1">
      <tbody>
            <tr>
                <th>Name 1</th>
                <th>Name 2</th>
                <th>Name 3</th>
                <th>Name 4</th>
            </tr>
            <tr>
                <td>Val</td>
                <td>Val</td>
                <td>Val</td>
                <td>Val</td>
            </tr>
            <tr>
                <td>Val</td>
                <td>Val</td>
                <td>Val</td>
                <td>Val</td>
            </tr>
        </tbody>
    </table>
    

    <table class="myclass" id="myid2">
    <tbody>
    <tr>
    <th>Name 1</th>
    <th>Name 2</th>
    <th>Name 3</th>
    <th>Name 4</th>
    </tr>
    <tr>
    <td>Val</td>
    <td>Val</td>
    <td>Val</td>
    <td>Val</td>
    </tr>
    <tr>
    <td>Val</td>
    <td>Val</td>
    <td>Val</td>
    <td>Val</td>
    </tr>
    </tbody>
    </table>


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2