0

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
J.dd
  • 145
  • 15
  • 5
    There 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 Jun 16 '16 at 09:15
  • You may want to look into the HTML5 [template](http://www.html5rocks.com/en/tutorials/webcomponents/template/) tag. – David Hedlund Jun 16 '16 at 09:18

1 Answers1

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.

Community
  • 1
  • 1
Jonny
  • 2,223
  • 23
  • 30