Willem de Wit
Willem de Wit

Reputation: 8732

Difference between creation of DOM elements in jQuery

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:

  1. By string:

    $('<a href="http://www.example.com" class="footerLink" rel="external">example</a>');`
    
  2. Create element first, add attributes later:

    $('<a></a>')
      .addClass('footerLink')
      .attr({ 
         rel: 'external, 
         href: 'http://www.example.com' 
      })
      .text('example');
    
  3. 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?

Upvotes: 4

Views: 636

Answers (2)

phtrivier
phtrivier

Reputation: 13357

As explained by Konstantin, the string approach is the better performance-wise. I would like to point out, however, that if the DOM string is not known at the time of writing the code (eg the text comes from user input), then the slower approach would make sense to :

  • avoid long series of string concatenations
  • give jquery's "text" method a chance to sanitize the string before outputing

In the end, this might really be a job for a templating framework (mustache or others...)

Upvotes: 0

Konstantin Dinev
Konstantin Dinev

Reputation: 34895

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():

var dom = '<a href="http://www.example.com" class="footerLink" rel="external">example</a>';
$(element).html(dom);

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.

// Assume we have data defined with 1000 data members
// each containing a text property
var list = [];
for (var i = 0; i < data.length; i++) {
    list.push('<li>' + data.text + '</li>');
}
$(ul).html(list.join(''));

Upvotes: 5

Related Questions