1

I was trying to create an html table from a nested for loop array in Javascript. When I try to append the <tr> tags to the table they get put in an element called tbody. How can I get the tr tags to be appended in the to the table element rather than the tbody element?

<html>
   <head>
        <script src='jq.js'></script>
   </head>
   <body>
       <table id='tb'></table>

   </body>
   <script>
       $('#tb').ready(     
        function() {
           console.log('table loaded');

          var ar = Array(2);

           for(var i=0;i<ar.length;i++){
              ar[i]=Array(2);
           }

           ar[0][0]='1';
           ar[1][0]='2';
           ar[0][1]='3';
           ar[1][1]='4';

           console.log('multidimensional array created!');

          for(var j=0;j<ar.length;j++){
              console.log('<tr>');
              $('#tb').append('<tr>');
              for(var k=0;k<2;k++){
                console.log('<td>'+ar[k][j]+'</td>');
                $('#tb').append('<td>'+ar[k][j]+'</td>');
              }
              console.log('</tr>');
              $('#tb').append('</tr>');
          }
          //expected:
          //12
          //34
          //actual
          //1 2 3 4
        });   
   </script>
</html>

Here's a jsfiddle

2
  • The body content of a table is contained within a <tbody> element. If one doesn't exist, modern browsers will add it. This is the way it is supposed to be. Dec 23, 2013 at 18:05
  • just so you know, you don't need to go to so much trouble initializing the array. Just do this: ar=[['1','2'],['3','4']]; it's that simple Dec 23, 2013 at 18:05

3 Answers 3

3

You can't. HTML tables are composed of three sections:

  • thead contains the header rows
  • tbody contains the data rows. You can have multiple of these if you want to make different groups of rows (e.g. if rows = months, you could have a separate tbody for each year).
  • tfoot contains the footer rows

If you put rows directly within the table tag, they're assumed to be part of tbody, and the browser creates this element automatically for you. You either have to put all your rows in tbody elements, or put them all directly within table.

The problem with your code has nothing to do with the tbody element. The problem is that you're trying to append td elements directly to the table, rather than to the tr elements. You're treating $('#tb').append() as if it's concatenating HTML text to the document, not inserting entire HTML elements. It should be something like:

     for(var j=0;j<ar.length;j++){
          console.log('<tr>');
          var row = $('<tr/>').appendTo('#tb');
          for(var k=0;k<2;k++){
            console.log('<td>'+ar[k][j]+'</td>');
            row.append('<td>'+ar[k][j]+'</td>'); // Append TD to TR
          }
      }

Or you can use CtrlX's answer, where he composes the entire table as a string, then inserts it into the DOM in one step. This is more efficient than building up the table incrementally.

1
  • Keep in mind that multiple tbody elements are allowed by specification.
    – 2C-B
    Jan 8, 2015 at 18:37
2

You shouldn't append content like this to your table, because the browser must redraw the whole DOM, so it's not very efficient.

You should build your table inside a string, then append the whole string to your table, like this :

$('#tb').ready(     
    function() {
       console.log('table loaded');

      var ar = Array(2);

       for(var i=0;i<ar.length;i++){
          ar[i]=Array(2);
       }

       ar[0][0]='1';
       ar[1][0]='2';
       ar[0][1]='3';
       ar[1][1]='4';

       console.log('multidimensional array created!');
        //Prepare the outputed string
       var theTable = "";
      for(var j=0;j<ar.length;j++){
          theTable += '<tr>';
          for(var k=0;k<2;k++){             
            theTable += '<td>'+ar[k][j]+'</td>';
          }
          theTable += '</tr>';
      }
       //Finally appended the whole string to the table
       $('#tb').append(theTable);
      //expected:
      //12
      //34
      //actual
      //1 2 3 4
    });   

I've made a Jsfiddle for you : JSFiddle

Have fun !

3
  • This is good advice, but it won't address his question about tbody.
    – Barmar
    Dec 23, 2013 at 18:08
  • If you look the code, it say : "//expected: ... //actual". So the "tbody question" is not really the point I think
    – CtrlX
    Dec 23, 2013 at 18:10
  • The difference in efficiency would be something like 1 dom change vs n^2 dom changes. This is the best solution. From Barmars answer I can see that the browser is automatically going to add whatever I try to append to the table to the tbody element. Dec 23, 2013 at 19:25
0
   <body>
       <table id='tb1'>
           <tbody id='tb'>
           </tbody>

       </table>

   </body>
   <script>
       $('#tb').ready(     
        function() {
           console.log('table loaded');

          var ar = Array(2);

           for(var i=0;i<ar.length;i++){
              ar[i]=Array(2);
           }

           ar[0][0]='1';
           ar[1][0]='2';
           ar[0][1]='3';
           ar[1][1]='4';

           console.log('multidimensional array created!');

          for(var j=0;j<ar.length;j++){

              $('#tb').append('<tr>');
              for(var k=0;k<2;k++){                
                $('#tb').append('<td>'+ar[k][j]+'</td>');
              }             
              $('#tb').append('</tr>');
          }
          //expected:
          //12
          //34
          //actual
          //1 2 3 4
        });   
   </script>
</html>

this is the working code, on this fiddle http://jsfiddle.net/fn4Wz/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.