8

Different ways to add to the DOM with jQuery

 2 years ago
source link: https://www.codesd.com/item/different-ways-to-add-to-the-dom-with-jquery.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Different ways to add to the DOM with jQuery

advertisements

Traditionally Ive been appending HTML content to the page like so:

var text='Some text';
var num=0;
$('#div').append('<div id="a'+num+'">'+text+'</div>');

But recently Ive been noticing a lot of this approach in other peoples code:

var text='Some text';
var num=0;
var newElement=$('<div></div>').text(text).prop('id','a'+num);
$('#div').append(newElement);

Can someone explain to me the advantages of the second approach, and whether I should move over to this approach or whether I should keep appending like I always have been.


The first one is way faster than the second, mainly because it is just concating some string and directly appending the html

While in the second, you're doing .text() and .prop() which is a bit over kill than string concatenation..

The jsperf test also proves that the first method is the way to go. Though the second one is more readable, the first is faster. You choose what you want.

In my laptop, the second method was 19% slower than the first.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK