Is there a general best practice for creating somewhat complex HTML elements in jQuery? I\'ve tried a few different ways.
First I tried using createElement and chaining
Since HTML5 there's the <template>
tag.
$(function () {
// Get template
var template = $("#template").html();
// Create a new row from the template
var $row = $(template);
// Add data to the row
$row.find("td[data-template='firstName']").text("Foo");
$row.find("td[data-template='lastName']").text("Bar");
// Add the row to the table
$("#table").append($row);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<template id="template">
<tr>
<td data-template="firstName"></td>
<td data-template="lastName"></td>
</tr>
</template>
<table id="table">
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>
</table>
You don't have to call document.createElement:
$('#existingContainer').append(
$('<div/>')
.attr("id", "newDiv1")
.addClass("newDiv purple bloated")
.append("<span/>")
.text("hello world")
);
There are all sorts of useful tools in jQuery for extending/ammending the DOM. Look at the various "wrap" methods for example.
Another possibility: for really big blobs of new content, you may be better off having your server prepare those (using the server-side templating system, whatever that is for you) and fetching those with $.load()
or some other ajax approach.
I like the templating language Handlebars.js