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
3 Answers
Reset to default 2There 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
版权声明:本文标题:JavaScript: document.createNode or plain html? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742043042a2417635.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论