This post was most recently updated on July 29th, 2024
This article provides the information about jQuery DOM insertion methods Difference and Performance. These methods are really matters for your page, It dramatically affects the performance of your page.
.html()
The .html() jQuery method set and return the content of selected elements. When this method is used to set content, It set the content for every matched element, any content in that element it completely replaced by new content. When this method is used to get content, It gets the only first matched element. These methods basically use JavaScript innerHTML property.
1 2 3 4 5 6 |
var listItem = ""; var listArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]; $.each( listArray, function( i, item ) { listItem += "<li>Item " + item + "</li>"; }); $( "#listItem" ).html( listItem ); |
.append()
The .append() jQuery method insert content to the end of the element in matched element.
1 2 3 4 5 |
var listArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]; $.each( listArray, function( i, item ) { var listItem = "<li>Item " + item + "</li>"; $( "#listItem" ).append( listItem ); }); |
.innerHTML()
The .innerHTML() property work like .html() jQuery method. innerHTML is a JavaScript property. The innerHTML property sets and gets the HTML content of matched element.
1 2 3 4 5 |
var listArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]; var list = document.getElementById('listItem'); $.each( listArray, function( i, item ) { list.innerHTML + "<li>Item " + item + "</li>"; }); |
For that, I create a test case demo to check the performance of all insert content methods. I found jQuery methods are faster than jQuery native property.
See the jQuery .html vs .append vs .innerHTML Performance Test Case Demo
If you’re wanting them to be nested mean after loop Native DOM property runs fast.
Native DOM methods are always faster than jQuery alternatives. However, .innerHTML is not ideal. jQuery seems faster compare to Native DOM methods because it prepares a string of with all the HTML first, where as the native DOM methods do one operation in each iteration. That’s why it takes time.
1 2 3 4 5 6 7 |
var listArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]; var list = document.getElementById('listItem'); var listItem = ""; $.each( listArray, function( i, item ) { listItem += "<li>Item " + item + "</li>"; }); list.innerHTML = listItem; |
So winner is html() followed by .append() followed by .InnerHTML().
Hope you find it helpful. If you liked this article, then please share and comment.
Is there an error in the inner html example?
shoud be
or am I wrong here?
Yes, it should be list.innerHTML += “Item ” + item + “” . Should add equal.