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:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…