I've seen a lot of different styles (and few different methods) of creating elements in jQuery. I was curious about the clearest way to build them, and also if any particular method is objectively better than another for any reason. Below are some examples of the styles and methods that I've seen.
var title = "Title";
var content = "Lorem ipsum";
// escaping endlines for a multi-line string
// (aligning the slashes is marginally prettier but can add a lot of whitespace)
var $element1 = $("\
<div><h1>" + title + "</h1>\
<div class='content'> \
" + content + " \
</div> \
</div> \
");
// all in one
// obviously deficient
var $element2 = $("<div><h1>" + title + "</h1><div class='content'>" + content + "</div></div>");
// broken on concatenation
var $element3 = $("<div><h1>" +
title +
"</h1><div class='content'>" +
content +
"</div></div>");
// constructed piecewise
// (I've seen this with nested function calls instead of temp variables)
var $element4 = $("<div></div>");
var $title = $("<h1></h1>").html(title);
var $content = $("<div class='content'></div>").html(content);
$element4.append($title, $content);
$("body").append($element1, $element2, $element3, $element4);
Please feel free to demonstrate any other methods/styles you might use.
You could possibly look into javascript view templates:
http://embeddedjs.com/
http://jupiterjs.com/news/jquery-view-client-side-templates-for-jquery
http://javascriptmvc.com/docs.html#!jQuery.View
My advice : don't try to build html elements with jQuery, it's not its responsability.
Use a Javascript templating system like Mustache or HandlebarJs.
With a very limited number of line, you can create your html elements directly from a Javascript object. It's not complicated, only 2 functions and a template.
Edit:
Another example without html, pure Javascript (from ICanHaz) :
It is much more maintainable than a series of concatenation.
When it comes to DOM building I try to avoid string concatenations as they might lead to subtle bugs and non properly encoded output.
I like this one:
generates:
and it ensures proper HTML encoding and DOM tree building with matching opening and closing tags.