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
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
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>
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
;