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.)
HTML 5 introduced the <template>
element which can be used for this purpose (as now described in the WhatWG spec and MDN docs).
A <template>
element is used to declare fragments of HTML that can be utilized in scripts. The element is represented in the DOM as a HTMLTemplateElement
which has a .content
property of DocumentFragment
type, to provide access to the template’s contents. This means that you can convert an HTML string to DOM elements by setting the innerHTML
of a <template>
element, then reaching into the template
‘s .content
property.
Examples:
/**
* @param {String} HTML representing a single element
* @return {Element}
*/
function htmlToElement(html) {
var template = document.createElement('template');
html = html.trim(); // Never return a text node of whitespace as the result
template.innerHTML = html;
return template.content.firstChild;
}
var td = htmlToElement('<td>foo</td>'),
div = htmlToElement('<div><span>nested</span> <span>stuff</span></div>');
/**
* @param {String} HTML representing any number of sibling elements
* @return {NodeList}
*/
function htmlToElements(html) {
var template = document.createElement('template');
template.innerHTML = html;
return template.content.childNodes;
}
var rows = htmlToElements('<tr><td>foo</td></tr><tr><td>bar</td></tr>');
Note that similar approaches that use a different container element such as a div
don’t quite work. HTML has restrictions on what element types are allowed to exist inside which other element types; for instance, you can’t put a td
as a direct child of a div
. This causes these elements to vanish if you try to set the innerHTML
of a div
to contain them. Since <template>
s have no such restrictions on their content, this shortcoming doesn’t apply when using a template.
However, template
is not supported in some old browsers. As of April 2021, Can I use… estimates 96% of users globally are using a browser that supports template
s. In particular, no version of Internet Explorer supports them; Microsoft did not implement template
support until the release of Edge.
If you’re lucky enough to be writing code that’s only targeted at users on modern browsers, go ahead and use them right now. Otherwise, you may have to wait a while for users to catch up.