Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to inject HTML into the DOM with jQuery?

I'm working on a calendar page that allows a user to click on a day, and enter an entry for that day with a form that pops up.

I'm no stranger to DOM manipulation with jQuery, but this is something I've done before and I'm beginning to wonder if there's a more efficient way to do this?

Would building the HTML manually within JavaScript be the most efficient way performancewise (I assume this is true, over using functions like appendTo() etc) or would creating a hidden construct within the DOM and then cloning it be better?

Ideally I want to know the optimal method of doing this to provide a balance between code neatness and performance.

Thanks,

Will

like image 428
Will Morgan Avatar asked Jun 23 '09 11:06

Will Morgan


People also ask

Where should I inject jQuery in HTML?

jQuery is embedded into the <script> tag of HTML file between the <head> tag and the <title> tag.

How do I get HTML using jQuery?

To get HTML content of an element using jQuery, use the html() method. The html() method gets the html contents of the first matched element.

What is the use of HTML () method in jQuery?

jQuery html() Method The html() method sets or returns the content (innerHTML) of the selected elements. When this method is used to return content, it returns the content of the FIRST matched element. When this method is used to set content, it overwrites the content of ALL matched elements.


2 Answers

Working with huge chunks of HTML strings in JavaScript can become very ugly very quickly. For this reason it might be worth considering a JavaScript "template engine". They needn't be complicated - Check out this one by Resig.

If you're not up for that then it's probably fine to just continue as you are. Just remember that DOM manipulation is generally quite slow when compared to string manipulation.

An example of this performance gap:

// DOM manipulation... slow
var items = ['list item 1', 'list item 2', 'list item 3'];
var UL = $('<ul/>');
$.each(items, function(){
    UL.append('<li>' + this + '</li>');
});

// String manipulation...fast
var items = ['list item 1', 'list item 2', 'list item 3'];
var UL = $('<ul/>').append( '<li>' + items.join('</li><li>') + '</li>' );
like image 194
James Avatar answered Sep 27 '22 17:09

James


Here you can find the explanation.

like image 33
Artem Barger Avatar answered Sep 27 '22 18:09

Artem Barger