Difference between creating DOM elements in jQuery

I am wondering if there is a performance difference (or best practice) when creating DOM elements using jQuery.

In my knowledge there are 3 ways to do this:

  • By line:

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

     $('<a></a>') .addClass('footerLink') .attr({ rel: 'external, href: 'http://www.example.com' }) .text('example'); 
  • Create an element and pass it an attribute:

     $('<a></a>', { 'class': 'footerLink', href: 'http://www.example.com', rel: 'external' }) .text('example'); 

EDIT: What if you add a lot of elements to an element? Should you make a very long string first and add that after the loop?

+4
source share
2 answers

The fastest way to create the entire DOM you want to add as a string, and then attach 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 third, for the reason that it does not need to perform any complex parsing of strings, and the attributes are not placed using a chain of function calls, but are provided as single objects in as a parameter for the selector.

There is a forum question in jQuery that you can check.

Update:

If you are creating many elements for an element, then you definitely need to use a string approach. Take a look at the following example of creating 1000 list items.

 // 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('')); 
+5
source

As Konstantin explained, the string approach is the best in performance. However, I would like to point out that if the DOM line is not known at the time of writing the code (for example, the text comes from user input), then a slower approach makes sense:

  • avoid long rows of string concatenations
  • give the jquery "text" method to sanitize the string before issuing

In the end, it really can be a job for the pattern structure (mustache or others ...)

0
source

Source: https://habr.com/ru/post/1439101/


All Articles