It is more readable and maintainable if the JavaScript code resembles the HTML tag structure, similar to the way that Luca answered.
I have gone about this a bit differently and made a function to make each element an editable jQuery object.
For example:
$$('div', {'id':'container'},
$$('div', {'id':'my_div'},
$$('h1',{'class':'my_header'},
$$('a',{'href':'/test/', 'class':'my_a_class'}, 'teststring'))));
Where the $$ function returns a jQuery object:
This makes the approach more flexible and you can add event handlers, data etc. to the nested jQuery objects using chaining quite easily.
For example:
$$('div', {'id':'container'},
$$('div', {'id':'my_div'},
$$('h1',{'class':'my_header'},
$$('a', { 'href': '/test/', 'class': 'my_a_class' }, 'teststring')
).click(function() { alert('clicking on the header'); })
).data('data for the div')
).hide();
You probably don't want to overdo it, but I still find the code more readable than if one were to use the best practice jQuery approach of doing it with separate calls to .append(), .text(), .html() etc. or by feeding the jQuery $ a concatenated HTML string.
Here is the reference $$ function (you can call it something else if you don't like it, but I thought $$ is appropriate since it returns a jQuery object and it is also short):
function $$(tagName, attrTextOrElems) {
// Get the arguments coming after the params argument
var children = [];
for (var _i = 0; _i < (arguments.length - 2) ; _i++) {
children[_i] = arguments[_i + 2];
}
// Quick way of creating a javascript element without JQuery parsing a string and creating the element
var elem = document.createElement(tagName);
var $elem = $(elem);
// Add any text, nested jQuery elements or attributes
if (attrTextOrElems) {
if (typeof attrTextOrElems === "string") { // text
var text = document.createTextNode(attrTextOrElems);
elem.appendChild(text);
}
else if (attrTextOrElems instanceof jQuery) { // JQuery elem
$elem.append(attrTextOrElems);
}
else // Otherwise an object specifying attributes e.g. { 'class': 'someClass' }
{
for (var key in attrTextOrElems) {
var val = attrTextOrElems[key];
if (val) {
elem.setAttribute(key, val);
}
}
}
}
// Add any further child elements or text
if (children) {
for (var i = 0; i < children.length; i++) {
var child = children[i];
if (typeof child === "string") { // text
var text = document.createTextNode(child);
elem.appendChild(text);
} else { // JQuery elem
$elem.append(child);
}
}
}
return $elem;
}