使用内置 DOM 方法或原型从 HTML 字符串创建新的 DOM 元素 [英] Creating a new DOM element from an HTML string using built-in DOM methods or Prototype
问题描述
我有一个表示元素的 HTML 字符串:'
.我想将它附加到 DOM 中的一个元素(在我的例子中是 ul
).如何使用 Prototype 或 DOM 方法执行此操作?
(我知道我可以在 jQuery 中轻松做到这一点,但不幸的是我们没有使用 jQuery.)
注意: 目前大多数浏览器都支持 HTML 元素,提供了更可靠的方式从字符串转换创建元素.有关详细信息,请参阅Mark Amery 在下方的回答.
对于较旧的浏览器和 node/jsdom:(在撰写本文时尚不支持 元素),请使用以下方法.这与库用来从 HTML 字符串中获取 DOM 元素的操作相同(对 IE 进行一些额外的工作 以解决其
innerHTML
实现的错误):
function createElementFromHTML(htmlString) {var div = document.createElement('div');div.innerHTML = htmlString.trim();//将此改为 div.childNodes 以支持多个顶级节点返回 div.firstChild;}
请注意,与 HTML 模板不同,这 不会适用于某些不能合法地成为
;s.如果您已经在使用库,我建议您坚持使用库认可的从 HTML 字符串创建元素的方法:
- Prototype 在其
update()
方法. - jQuery 在其
jQuery(html)
中实现了它和 jQuery.parseHTML
方法.
I have an HTML string representing an element: '<li>text</li>'
. I'd like to append it to an element in the DOM (a ul
in my case). How can I do this with Prototype or with DOM methods?
(I know i could do this easily in jQuery, but unfortunately we're not using jQuery.)
解决方案 Note: most current browsers support HTML <template>
elements, which provide a more reliable way of turning creating elements from strings. See Mark Amery's answer below for details.
For older browsers, and node/jsdom: (which doesn't yet support <template>
elements at the time of writing), use the following method. It's the same thing the libraries use to do to get DOM elements from an HTML string (with some extra work for IE to work around bugs with its implementation of innerHTML
):
function createElementFromHTML(htmlString) {
var div = document.createElement('div');
div.innerHTML = htmlString.trim();
// Change this to div.childNodes to support multiple top-level nodes
return div.firstChild;
}
Note that unlike HTML templates this won't work for some elements that cannot legally be children of a <div>
, such as <td>
s.
If you're already using a library, I would recommend you stick to the library-approved method of creating elements from HTML strings:
- Prototype has this feature built-into its
update()
method.
- jQuery has it implemented in its
jQuery(html)
and jQuery.parseHTML
methods.
这篇关于使用内置 DOM 方法或原型从 HTML 字符串创建新的 DOM 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文
登录
关闭
扫码关注1秒登录
发送“验证码”获取
|
15天全站免登陆