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 class="' + class_var + '">' + 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.
Written by Alex Cheuk
Related protips
13 Responses
Alex, this is really cool.
"There is nothing wrong with the above methods". I'd really say any string concatenation should probably be avoided since (if the class name is influenced by some external input) it can lead to an XSS vulnerability.
Interesting but chaining methods is way faster!
http://jsperf.com/jquery-different-ways-to-create-dom-elements
i prefer chaining method.
i makes thing easier and readable.
http://jsbin.com/IGaCuTe/2/edit?html,js,output
chaining is wonderful while creating dom if you creating doms like table rows.
http://jsbin.com/AwipUrer/2/edit?html,js,output
this is very useful, thanks
Nice tip. Thanks.
"As of jQuery 1.4, any event type can be passed in, and the following jQuery methods can be called: val, css, html, text, data, width, height, or offset." -- http://api.jquery.com/jquery/#jQuery-html-attributes
For example:
$('<img>', {
'class': 'avatar',
src: 'avatar.jpg',
css: {
maxWidth: '300px', maxHeight: '300px',
display: none
},
data: {
capture: 'true'
}
})
</code></pre>
Cool.. Nice tip... :)
I don't think this is a tip, as jQuery docs themselves mention it.
http://api.jquery.com/jquery/#example-1-1.
A tip would be something unusual, that helped an original problem.
Also, $('<div/>', { ... })
is an incredibly slow method.
$( document.createElement('div'), { ... })
can be a more faster alternative.
Also, if you had reference to document
in a local variable, say doc
, doc.createElement
would be more optimised.
Yup, chaining is faster, didn't even know about the Object method of doing this (RTFM).
But for readability, I like the Object method.
IMHO, better to do something like this:
$(document.createElement('div'), { ... })
Created a jsPerf to really see which method is faster, http://jsperf.com/jquery-vanilla-js-dom-creation
For some reason my test give different results for chaining then the tests from alexcheuk.
The best tip is not to use jQuery to create elements.