I am loading data from JSON and want to display it on the site. Needless to say, each data section should have its own space e.g., div, etc.
My question: is there better way how to put this data on web then creating new div and then appending it to the container for each data section?
e.g
var div = document.createElement("div");
div.onclick = doSomething;
var p = document.createElement("p");
p.innerHTML = json_response[0].name;
div.appendChild(p);
document.body.appendChild(p)
Wouldn't this be too slow for the vast amount of data? Is there a more valid way?
-
5There are lots of ways to do this in an optimized way. But unless you absolutely have to do it in core js I would suggest you take a look at a framework (React, Angular?)Anders Bornholm– Anders Bornholm2016年06月16日 09:15:53 +00:00Commented Jun 16, 2016 at 9:15
-
You may want to look into the HTML5 template tag.David Hedlund– David Hedlund2016年06月16日 09:18:17 +00:00Commented Jun 16, 2016 at 9:18
1 Answer 1
You could create each section in one of these two ways:
function createSection(name) {
const template = document.createElement('template');
template.innerHTML = `
<div>
<p>${name}</p>
</div>
`;
return template;
}
See https://stackoverflow.com/a/25214113/2106834 for more details.
function template(strings, ...keys) {
return (function(...values) {
var dict = values[values.length - 1] || {};
var result = [strings[0]];
keys.forEach(function(key, i) {
var value = Number.isInteger(key) ? values[key] : dict[key];
result.push(value, strings[i + 1]);
});
return result.join('');
});
}
const templateClosure = template`
<div>
<p>${'name'}</p>
<p>${'someOtherKeyInYourObject'}</p>
</div>`;
let n;
for(n = 0; n < json_response; n++) {
templateClosure(json_response[n]); // returns your HTML string
}
See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals#Tagged_template_literals for more detials.