Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: document.createNode or plain html?

Is it better to use

document.createNode();

or plain text like

var foo = '<div> bar </div>';

to create HTML markup with JavaScript?

like image 738
Louner Avatar asked Oct 11 '22 08:10

Louner


2 Answers

There is no "better" in this particular case, it is going to boil down to what is most easily maintained. and programmer preference.

In some browsers, using DOM to create elements and nodes is, in terms of performance, faster than others. Some user agents process strings faster, for example by setting the innerHTML property.

I personally prefer to use DOM objects always, but I use the mootools framework which lends itself to this approach. jQuery encourages string-based creation.

Check out this benchmark: http://jsperf.com/string-vs-createelement/3, but also consider these articles: http://www.quirksmode.org/dom/innerhtml_old.html and http://karma.nucleuscms.org/item/101

like image 199
Chris Baker Avatar answered Oct 13 '22 02:10

Chris Baker


It is better to use the DOM node functions. If you want to create it using a string, look into jQuery, as it has ways to parse it correctly into DOM nodes for you.

var foo = $('<div> bar </div>');
like image 34
Alex Turpin Avatar answered Oct 13 '22 04:10

Alex Turpin