admin管理员组

文章数量:1318336

Is it better to use

document.createNode();

or plain text like

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

to create HTML markup with JavaScript?

Is it better to use

document.createNode();

or plain text like

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

to create HTML markup with JavaScript?

Share Improve this question edited Aug 1, 2011 at 17:01 Louner asked Aug 1, 2011 at 15:53 LounerLouner 1052 silver badges5 bronze badges 1
  • 7 Better for what? Readability? Performance? Something else? – Oded Commented Aug 1, 2011 at 15:54
Add a ment  | 

3 Answers 3

Reset to default 2

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./string-vs-createelement/3, but also consider these articles: http://www.quirksmode/dom/innerhtml_old.html and http://karma.nucleuscms/item/101

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>');

Using DOM manipulation functions you can have a reference to the created elements, one by one, and will be easier to modify the code later on, for example modify the tree order, adding or removing an element, and also for debugging purposes.

This said, there are some times I experienced myself in which the DOM manipulation functions are not the best way.

For example I had the necessity to modify real time the content of a style tag, to control the style of the elements directly via text css rules, something you can't achieve in all browsers using the various JS style objects, because they contain read-only properties.

In this case the style tag html was read-only for IE (or at least IE didn't like to modify it via innerHtml or similar), the only solution I found was to read the old html value, change it, remove the element and create a new style tag element with the new html directly typed in the string when creating the element.

This said, I would go with the DOM node functions whenever possible.

本文标签: JavaScript documentcreateNode or plain htmlStack Overflow