Mayank
Mayank

Reputation: 954

Create full table structure dynamicaly with single loop with Javascript

I need to create tabel which could have multiple rows. I creating table on run time with javascript . As of now did that with two loop

exlTb = document.getElementById('exlTb');
tbl = document.createElement('table');
tbdy = document.createElement('tbody');

for(var i=0; i <= row; i++){
    var tr=document.createElement('tr');
    for(var j = 0; j <= colomn; j++){
      var td = document.createElement('td'); 
      tr.appendChild(td);
      }
    tbdy.appendChild(tr);  
   }
 tbl.appendChild(tbdy);
 exlTb.appendChild(tbl);

I am trying to optimize my solution

Upvotes: 0

Views: 568

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074425

If your goal is to create the table more quickly, all those trips to and from the DOM layer are something you can get rid of. Browsers are really really fast at parsing HTML. When building tables dynamically like this, you're usually better off creating markup and then having the browser parse and create it all at once, because you're not crossing that JavaScript/DOM boundary all the time.

Here's one way:

exlTb = document.getElementById('exlTb');
var markup = ['<table><tbody>'];

for(var i=0; i <= row; i++){
    markup.push('<tr>');
    for(var j = 0; j <= colomn; j++){
      markup.push('<td></td>');
      }
    markup.push('</tr>');
   }
markup.push('</tbody></table>');
exlTb.innerHTML = markup.join(""); // <== Note: Assumes exlTb is otherwise empty

Building the markup up in an array and then combining it once at the end is quicker in many (but not all) cases than string concatenation. I expect if you look around, there's a http://jsperf.com test already out there comparing...

Upvotes: 2

Related Questions