proper way (rows & cols & the random innerText is set dynamically ...by you)
this way is probably not the shortest but by way the fastest to build a table.
It’s also a full table with thead
and filled with random text:
use native JavaScript (not slowing down JQuery)
(function(){})()
executes the code before body is loading
doesn’t have problems with other variables outside the function
and pass the document so you have shorter variables
there is a way to shorten the function by using clone node... but it’s slower and maybe not supported by all browsers
use createDocumentFragment()
to create the tr
’s. If you have a lot of rows this helps to build the DOM faster.
(function (d) {
var rows = 10,
cols = 3,
t = d.createElement('table'),
the = d.createElement('thead'),
tb = d.createElement('tbody'),
tr = d.createElement('tr');
t.style.width = "100%";
t.style.borderCollapse = 'collapse';
for (var a = 0; a < cols; a++) {
var th = d.createElement('th');
th.innerText = Math.round(Math.random() * 100);
tr.appendChild(th);
};
the.appendChild(tr);
var f = d.createDocumentFragment();
for (var a = 0; a < rows; a++) {
var tr = d.createElement('tr');
for (var b = 0; b < cols; b++) {
var td = d.createElement('td');
td.innerText = Math.round(Math.random() * 100);
tr.appendChild(td);
}
f.appendChild(tr);
}
tb.appendChild(f);
t.appendChild(the);
t.appendChild(tb);
window.onload = function () {
d.body.appendChild(t)
};
})(document)