Add row to the beginning of a table – JavaScript – jQuery

What is the best method in jQuery to add an additional row to a table as the first row?

I have a table like this

<table id="mytable" cellpadding="0" cellspacing="0">
  <tr>
    <td>col1</td>
    <td>col2</td>
    <td>col3</td>
  </tr>
  <tr>
    <td>col1</td>
    <td>col2</td>
    <td>col3</td>
  </tr>
</table>
<button id="but">mybutton</button>

I want to add a row as the first row to the beginning of the table with given default values. How can I accomplish this using JavaScript and jQuery? A fiddle will be helpful.

6 thoughts on “Add row to the beginning of a table – JavaScript – jQuery”

  1. Folloing is what I am doing

    Template

    <script type="text/template" id="cardTemplate">
        <TR class=Normal>
            <TD>
                    {0}
            </TD>
            <TD>
                    {1}
            </TD>
            <TD>
                    {2}
            </TD>
    
         </TR>
    </script>
    

    jQuery

           String.prototype.format = function() {
                                     var args = arguments;
                                     return this.replace(/{(\d+)}/g, function(match, number) { 
                                            return typeof args[number] != 'undefined'
                                                   ? args[number]
                                                   : match
                                                  ;
                                              });
                                      };
    
                    var cardTemplate = $("#cardTemplate").html();
                    //Note: format is a custom method added for "String"
                    var template = cardTemplate.format("a", "b","c");
    
                    //$('#tblScanResult tbody > tr:first').before(template);
                    $('#tblScanResult tbody').prepend(template);
    
    Reply
  2. The accepted answer is good, but it is definitely worth noting that the tbody is the node you should append/prepend to, and using the appendTo and prependTo methods is the best solution as it will work when there are any number of rows, including zero.

    See this answer for a good example: https://stackoverflow.com/a/1353736/2812428

    Note also that it is good practice to specify a tbody yourself, even if there are no rows, to avoid the issue that there would be no tbody automatically in the DOM in the case that there were no rows added to the table.

    Reply

Leave a Comment