jQuery DOM creation tips

I want to share a neat little trick with jQuery DOM creation.

I often see jQuery scripts create DOM elements like this:

var $elem = $('<div>' + text + '</div>');
// OR
var $elem = $("<div>").addClass('some-class').text("text content");

There is nothing wrong with the above methods, but you can actually pass in an object to extend the element being created like so:

var $elem = $('<div/>', {
    "class" : "some-class",
    "attr" : "value",
    "text" : "text content", // equivalent to .text()
    "html" : "<h3>title</h3>", // equivalent to .html()
    "click" : function() { } // click event

Using this method, you can create an DOM using a predefined object and stay away from nasty string concatenations.