2

I want to know how to create and append HTML using jQuery. Obviously it's tedious to write 20-25 or even more line of codes like this:

 "<h1>"+response.name+"</h1>" +
   "<p>"+response.description+"</p>" + and so on
2
  • 1
    Sounds like you just need a loop. Without seeing any more useful parts of your logic, such as the contents of the data structure you're manually writing 25 times, or how you're appending this HTML, we can't really offer you any useful guidance. Commented Jul 26, 2018 at 9:03
  • 1
    If the code is exactly the same for those 20-25 lines, then you can hardcode that HTML code in your script and then apply a loop to append that HTML in the parent div. If the code is a bit different but the DOM structure is same, then you can generate the HTML first and then use the loop to append the data in the HTML. Commented Jul 26, 2018 at 9:20

2 Answers 2

1

If you have a (more or less) fixed markup structure and repeatedly want to fill that with variable values, you might consider using templates.

There are tons of templating-engines for JS, but too keep things simple here is an example using mustache.js:

<script src="mustache.js" type="text/javascript"></script>

<script id="template" type="x-tmpl-mustache">
    <h1>{{name}}</h1>
    <p>{{description}}</p>
    {{#optionalVar1}}
        <p>{{#optionalVar1}}</p>
    {{/optionalVar1}}
</script>

<script type="text/javascript">
    var template = document.querySelector('#template').innerHTML;

    /* "response" should be an object containing named members as
     * in the template above. "{{name}}" refers to "response.name" */
    var rendered = Mustache.render(template, response);
    document.querySelector('#output').innerHTML = rendered;
</script>
Sign up to request clarification or add additional context in comments.

Comments

0

Here is an example to create and append html in jQuery

$('body').append($('h1').text(response.name))
   .append($('p').text(response.description))
   ... append as much as you want
;

2 Comments

Which will only make the code from the question more verbose.
It only append a single instance too. The OP explicitly states they are doing this 20-25 times.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.