jQuery - Best Practice for creating complex HTML Fragments

With jQuery 1.4, you can create HTML elements like so:

// create an element with an object literal, defining properties
var e = $("<a />", {
    href: "#",
    "class": "a-class another-class", // you need to quote "class" since it's a reserved keyword
    title: "..."
});

// add the element to the body
$("body").append(e);

Here's a link to the documentation.

I'm not sure that this approach is faster than using the html() function of jQuery. Or faster than skipping jQuery all together and use the innerHTML property on an element. But as far as readability goes; the jQuery-approach is my favorite. And in most cases the performance-gain of using innerHTML is marginal.


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'd be inclined to look at one of the templating engines for jquery like jQote


John Resig (creator of jQuery) suggested using this templating method back in 2008. It's actually got some pretty cool features:

<script type="text/html" id="item_tmpl">

  <div id="<%=id%>" class="<%=(i % 2 == 1 ? " even" : "")%>">
    <div class="grid_1 alpha right">
      <img class="righted" src="<%=profile_image_url%>"/>
    </div>
    <div class="grid_6 omega contents">
      <p><b><a href="/<%=from_user%>"><%=from_user%></a>:</b> <%=text%></p>
    </div>
  </div>

</script>

then retrieving it using...

var results = document.getElementById("results");
results.innerHTML = tmpl("item_tmpl", dataObject);

See here for full details:
http://ejohn.org/blog/javascript-micro-templating/