I’m wondering if there is a difference in performance (or what is the best practice) in creating DOM elements with jQuery.
By my knowlegde there are 3 ways to do this:
-
By string:
$('<a href="http://www.example.com" class="footerLink" rel="external">example</a>');` -
Create element first, add attributes later:
$('<a></a>') .addClass('footerLink') .attr({ rel: 'external, href: 'http://www.example.com' }) .text('example'); -
Create element and pass attributes object with it:
$('<a></a>', { 'class': 'footerLink', href: 'http://www.example.com', rel: 'external' }) .text('example');
EDIT:
What if you are appending a lot of items to an element? Should you make a very long string first and append that after the loop?
The fastest way for you to be to create the entire DOM you want to attach as string and then attach it to the document as
html():Of the three that you have in your example the fastest should be the 3rd one, for the reason that it does not have to do any complex string parsing and the attributes are not put using chained function calls but are provided as a single object as a parameter to the selector.
There is a forum thread on jQuery you may want to check out.
Update:
If you are creating a lot of items to an element, then you should definitely take the string approach. Take a look at the following example of making a 1000 list elements.