Search code examples
javascriptjqueryhtml

Row added twice to table with jQuery


I want to create a table with jquery. My code is like this:

function showGrid(url, container, columns, page) {
    jQuery(container).empty();

    var tr = jQuery("<tr class=\"mobileGridHeader\"><tr>");

    var tdTotalRows = jQuery("<td>test</td>");
    jQuery(tr).append(tdTotalRows);

    var table = jQuery('<table class="mobileGrid"></table>');
    jQuery(table).append(tr);

    jQuery(container).append(table);
}

The container is a div on the page. The problem is, that the tr is added twice to the container and I do not know why.

enter image description here

It is not just a Browser error, in the Html I can see the code twice.

<table class="mobileGrid">
   <tbody>
       <tr class="mobileGridHeader">
           <td>test</td>
       </tr>
       <tr>
           <td>test</td>
       </tr>
   </tbody>
</table>

The weird is also, that the css class "mobileGridHeader" is only added in the first row.


Solution

  • You do not close tr tag in your creation so 2 elements are created. To fix the issue instead of this line:

    var tr = jQuery("<tr class=\"mobileGridHeader\"><tr>");
    

    use this line (backslash added):

    var tr = jQuery("<tr class=\"mobileGridHeader\"></tr>");