For these samples, I am using Bootstrap in order to have a nice appearance for my web page. However, Bootstrap is not required for these samples. The HTML I am using creates an empty table with just a <thead> for the headers of each column in the table. Note that there is no <tbody>. We will check for that in our jQuery and add one if necessary.
Adding a Row
Within the <script> tag, create a function called addRows(). This function is where you will use the append() method to add a <tr> with the appropriate number of <td> tags to form a row for your table. Use a jQuery selector to locate the id attribute of your table, and the <tbody> tag and append a <tr> and the <td> tags as shown in the code below:
If you read the HTML I posted earlier, you will notice that I did not include a <tbody> tag within the table. So, if you were to run the addRows() function, then no rows will be appended to your table because the result of the selector comes back as nothing. First off, you really should always have a <tbody> in all of your tables. However, if you don’t, then no problem, you can always add one programmatically. First check to see if the selector of your table id and the <tbody> returns something. If it does not, then simply append a <tbody> tag to the table prior to calling the append() with the rows you wish to add. You do this with the code shown below:
So, our complete method to add a couple or rows to our HTML table, looks like the code shown below:
You can call the above function when the document is loaded by adding the jQuery document.ready function just before the ending </script> tag.