How to add table row in a table using jQuery?

jQuery can be used to add table rows dynamically. This can be used in web applications where the user may need to add more rows if required.

Steps to add table row:

  • The required markup for the row is constructed.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    markup = "<tr><td> + information + </td></tr>"

    chevron_right

    
    

  • The table body is selected to which the table rows to be added.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    tableBody = $("table tbody")

    chevron_right

    
    

  • Finally the markup is added to the table body.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    tableBody.append(markup)

    chevron_right

    
    

Example:



filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        How to add table row in jQuery?
    </title>
      
    <script src=
    </script>
      
    <style>
        table {
            margin: 25px 0;
            width: 200px;
        }
  
        table th, table td {
            padding: 10px;
            text-align: center;
        }
  
        table, th, td {
            border: 1px solid;
        }
    </style>
</head>
  
<body>
    <h1 style="color: green">
        GeeksForGeeks
    </h1>
      
    <b>How to add table row in jQuery?</b>
      
    <p>
        Click on the button below to
        add a row to the table
    </p>
      
    <button class="add-row">
        Add row
    </button>
      
    <table>
        <thead>
            <tr>
                <th>Rows</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>This is row 0</td>
            </tr>
        </tbody>
    </table>
      
    <!-- Script to add table row -->
    <script>
        let lineNo = 1;
        $(document).ready(function () {
            $(".add-row").click(function () {
                markup = "<tr><td>This is row " 
                    + lineNo + "</td></tr>";
                tableBody = $("table tbody");
                tableBody.append(markup);
                lineNo++;
            });
        }); 
    </script>
</body>
</html>                    

chevron_right


Output:

  • Before clicking the button:
    before-click
  • After clicking the button 4 times:
    after-click


My Personal Notes arrow_drop_up

Technical Writer Lets have an update

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.