Note: most current browsers support HTML <template>
elements, which provide a more reliable way of turning creating elements from strings.
(注意:当前大多数浏览器都支持HTML <template>
元素,该元素提供了一种更可靠的方式来转换从字符串创建元素的方式。)
See Mark Amery's answer below for details .(有关详细信息,请参见下面的Mark Amery的答案 。)
For older browsers, and node/jsdom : (which doesn't yet support <template>
elements at the time of writing), use the following method.
(对于较旧的浏览器和node / jsdom :(在撰写本文时尚不支持<template>
元素),请使用以下方法。)
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
):(库用于从HTML字符串中获取DOM元素的方法是相同的( IE还要做一些额外的工作来解决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.
(请注意,与HTML模板不同,这不适用于某些不能合法地成为<div>
子元素的元素,例如<td>
。)
If you're already using a library, I would recommend you stick to the library-approved method of creating elements from HTML strings:
(如果您已经在使用库,建议您坚持使用库批准的从HTML字符串创建元素的方法:)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…