J.dd
J.dd

Reputation: 157

Dynamically creating html

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?

Upvotes: 0

Views: 93

Answers (1)

Jonny
Jonny

Reputation: 2333

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.

Upvotes: 1

Related Questions