What is the most efficient way to create HTML elements using jQuery?
JavascriptJqueryHtmlDomJavascript Problem Overview
Recently I've been doing a lot of modal window pop-ups and what not, for which I used jQuery. The method that I used to create the new elements on the page has overwhelmingly been along the lines of:
$("<div></div>");
However, I'm getting the feeling that this isn't the best or the most efficient method of doing this. What is the best way to create elements in jQuery from a performance perspective?
This answer has the benchmarks to the suggestions below.
Javascript Solutions
Solution 1 - Javascript
I use $(document.createElement('div'));
Benchmarking shows this technique is the fastest. I speculate this is because jQuery doesn't have to identify it as an element and create the element itself.
You should really run benchmarks with different Javascript engines and weigh your audience with the results. Make a decision from there.
Solution 2 - Javascript
personally i'd suggest (for readability):
$('<div>');
some numbers on the suggestions so far (safari 3.2.1 / mac os x):
var it = 50000;
var start = new Date().getTime();
for (i = 0; i < it; ++i) {
// test creation of an element
// see below statements
}
var end = new Date().getTime();
alert( end - start );
var e = $( document.createElement('div') ); // ~300ms
var e = $('<div>'); // ~3100ms
var e = $('<div></div>'); // ~3200ms
var e = $('<div/>'); // ~3500ms
Solution 3 - Javascript
Question:
> What is the most efficient way to create HTML elements using jQuery?
Answer:
Since it's about jQuery
then I think it's better to use this (clean) approach (you are using)
$('<div/>', {
'id':'myDiv',
'class':'myClass',
'text':'Text Only',
}).on('click', function(){
alert(this.id); // myDiv
}).appendTo('body');
This way, you can even use event handlers for the specific element like
$('<div/>', {
'id':'myDiv',
'class':'myClass',
'style':'cursor:pointer;font-weight:bold;',
'html':'<span>For HTML</span>',
'click':function(){ alert(this.id) },
'mouseenter':function(){ $(this).css('color', 'red'); },
'mouseleave':function(){ $(this).css('color', 'black'); }
}).appendTo('body');
But when you are dealing with lots of dynamic elements, you should avoid adding event handlers
in particular element, instead, you should use a delegated event handler, like
$(document).on('click', '.myClass', function(){
alert(this.innerHTML);
});
var i=1;
for(;i<=200;i++){
$('<div/>', {
'class':'myClass',
'html':'<span>Element'+i+'</span>'
}).appendTo('body');
}
So, if you create and append hundreds of elements with same class, i.e. (myClass
) then less memory will be consumed for event handling, because only one handler will be there to do the job for all dynamically inserted elements.
Update : Since we can use following approach to create a dynamic element
$('<input/>', {
'type': 'Text',
'value':'Some Text',
'size': '30'
}).appendTo("body");
But the size
attribute can't be set using this approach using jQuery-1.8.0
or later and here is an old bug report, look at this example using jQuery-1.7.2
which shows that size
attribute is set to 30
using above example but using same approach we can't set size
attribute using jQuery-1.8.3
, here is a non-working fiddle. So, to set the size
attribute, we can use following approach
$('<input/>', {
'type': 'Text',
'value':'Some Text',
attr: { size: "30" }
}).appendTo("body");
Or this one
$('<input/>', {
'type': 'Text',
'value':'Some Text',
prop: { size: "30" }
}).appendTo("body");
We can pass attr/prop
as a child object but it works in jQuery-1.8.0 and later
versions check this example but it won't work in jQuery-1.7.2 or earlier
(not tested in all earlier versions).
BTW, taken from jQuery
bug report
> There are several solutions. The first is to not use it at all, since > it doesn't save you any space and this improves the clarity of the > code:
They advised to use following approach (works in earlier ones as well, tested in 1.6.4
)
$('<input/>')
.attr( { type:'text', size:50, autofocus:1 } )
.val("Some text").appendTo("body");
So, it is better to use this approach, IMO. This update is made after I read/found this answer and in this answer shows that if you use 'Size'(capital S)
instead of 'size'
then it will just work fine, even in version-2.0.2
$('<input>', {
'type' : 'text',
'Size' : '50', // size won't work
'autofocus' : 'true'
}).appendTo('body');
Also read about prop, because there is a difference, Attributes vs. Properties
, it varies through versions.
Solution 4 - Javascript
Actually, if you're doing $('<div>')
, jQuery will also use document.createElement()
.
(Just take a look at line 117).
There is some function-call overhead, but unless performance is critical (you're creating hundreds [thousands] of elements), there isn't much reason to revert to plain DOM.
Just creating elements for a new webpage is probably a case in which you'll best stick to the jQuery way of doing things.
Solution 5 - Javascript
If you have a lot of HTML content (more than just a single div), you might consider building the HTML into the page within a hidden container, then updating it and making it visible when needed. This way, a large portion of your markup can be pre-parsed by the browser and avoid getting bogged down by JavaScript when called. Hope this helps!
Solution 6 - Javascript
This is not the correct answer for the question but still I would like to share this...
Using just document.createElement('div')
and skipping JQuery will improve the performance a lot when you want to make lot of elements on the fly and append to DOM.
Solution 7 - Javascript
I think you're using the best method, though you could optimize it to:
$("<div/>");
Solution 8 - Javascript
You don't need raw performance from an operation you will perform extremely infrequently from the point of view of the CPU.
Solution 9 - Javascript
You'll have to understand that the significance of element creation performance is irrelevant in the context of using jQuery in the first place.
Keep in mind, there's no real purpose of creating an element unless you're actually going to use it.
You may be tempted to performance test something like $(document.createElement('div'))
vs. $('<div>')
and get great performance gains from using $(document.createElement('div'))
but that's just an element that isn't in the DOM yet.
However, in the end of the day, you'll want to use the element anyway so the real test should include f.ex. .appendTo(
Let's see, if you test the following against each other:
var e = $(document.createElement('div')).appendTo('#target');
var e = $('<div>').appendTo('#target');
var e = $('<div></div>').appendTo('#target');
var e = $('<div/>').appendTo('#target');
You will notice the results will vary. Sometimes one way is better performing than the other. And this is only because the amount of background tasks on your computer change over time.
So, in the end of the day, you do want to pick the smallest and most readable way of creating an element. That way, at least, your script files will be smallest possible. Probably a more significant factor on the performance point than the way of creating an element before you use it in the DOM.
Solution 10 - Javascript
Someone has already made a benchmark: https://stackoverflow.com/questions/268490/jquery-document-createelement-equivalent
$(document.createElement('div'))
is the big winner.
Solution 11 - Javascript
One point is that it may be easier to do:
$("<div class=foo id=bar style='color:white;bgcolor:blue;font-size:12pt'></div>")
Then to do all of that with jquery calls.
Solution 12 - Javascript
I am using jquery.min v2.0.3 . It's for me better to use following:
var select = jQuery("#selecter");
jQuery("`<option/>`",{value: someValue, text: someText}).appendTo(select);
as following:
var select = jQuery("#selecter");
jQuery(document.createElement('option')).prop({value: someValue, text: someText}).appendTo(select);
Processing time of first code is much lower than second code.