How to create multiple HTML elements with jQuery?
$('First Element').add($('Second Element')).appendTo($('body'))
String concatenation (or Array.join) is fine, as long as you make it pretty ;)
var structure = [
'<div id="something">',
'<span>Hello!</span>',
'</div>'
];
$(structure.join('')).appendTo(container);
There is always append().
$('#container').append('<span>foobar baz</span>');
It seems to me that just using string concatenation and append would be the least complex, and probably fastest option. However, following is an untested example of a way to (arguably) simplify the creation of elements, and allow you to append them to a given parent element:
function elemCreate(type, content, attrs) {
/* type: string tag name
* content: string element content
* attrs: associative array of attrs and values
*/
elem = '<' + type + '></' + type + '>'
e = $(elem).attr(attrs)
e.append(content)
return e
}
stuff = [];
stuff.push(elemCreate('a', 'Click me!', {'href': 'http://stackoverflow.com'});
$(stuff).appendTo($('#container'));