I should probably just be thankful you actually used TH and CAPTION unlike most people, but where's your THEAD and TBODY? Where's your SCOPE? There's more that goes into a well formed table than TR and TD.

Also what's with the goofball class -- that's not even real world deployable on websites yet -- for what could simply -- and most likely "real world" would be -- JSON?

I would probably not even have talked about the insecure wreck that is innerHTML. It's an outdated, outmoded approach, where if you use it for "client data" you're just begging for an XSS exploit.

Much less the massive waste of RAM you have with the derpy string addition.

Your DOM approach is'nae much better, what with the pointless constants, failure to leverage appendChild's return, variables for nothing, and a constant repetition one simple function could have avoided.

Even just blind building to walk the DOM could have saved a ton of effort, as then the only element you'd need is the TBODY.

Likewise it probably wouldn't have hurt to make it more generic so you can pass the caption and associated data to the function, as well as the targetID to plug the table into.

(function(d) {function elementMake(tagName, parent, content) {
var e = d.createElement(tagName);
if (content) e.appendChild(
content instanceof Node ? content : d.createTextNode(content)
);
if (parent) parent.appendChild(e);
return e;
} // elementMake
function tableMake(data, targetId) {var
table = elementMake(
"table",
d.getElementById(targetId),
elementMake("caption", null, data.caption)
),
tr = elementMake("tr", elementMake("thead", table)),
tbody = elementMake("tbody", table);
for (var thText of data.thead) {
elementMake("th", tr, thText).scope = "col";
}
for (var row of data.tbody) {
tr = elementMake("tr", tbody);
for (var [key, value] of Object.entries(row)) elementMake(
tr.firstElementChild ? "td" : "th",
tr,
value
);
tr.firstElementChild.scope = "row";
}
} // tableMakevar Elements = {
caption : "Elements",
thead : [
"Name", "Atomic Number", "Chemical Symbol"
],
tbody : [
{
name: "Hydrogen",
atomicnumber: 1,
symbol: "H"
}, {
name: "Helium",
atomicnumber: 2,
symbol: "He"
}
]
};
tableMake(Elements, "tableDiv");})(document);

See, easy-peasy lemon squeezy. A simple “elementMake” — like what react does under the hood once it “compiles” — reduces the overall excess. And it’s still dozens of times faster executing that string addition and innerHTML, even with the extra function call overhead.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store