在以下示例中,从包含 HTML 的字符串创建 HTMLCollection。
是否可以最终将 HTML 集合添加到另一个元素中,而无需添加额外的周围 div 或模板元素?
const stringHTML = `
<div>
<h1>This is a div</h1>
<div>
<p>inner div</p>
</div>
</div>
<div>
<h2>Another div</h2>
</div>
`;
/**
* @param html {String} Representing a single HTML element
* @return {HTMLCollection} The newly created element
*/
const stringToHTMLCollection = function(html) {
/** @type {HTMLElement} */
const template = document.createElement('template');
html = html.trim(); // Never return a text node of whitespace as the result
template.innerHTML = html;
return template.content.children;
}
console.log(stringToHTMLCollection(stringHTML));
// This works.
Object.entries(stringToHTMLCollection(stringHTML)).forEach(([key, element]) => {
result.insertAdjacentElement('beforeend', element);
});
// However isn't there a more elegant way using something similar to insertAdjecentHTML?
<div id="result"></div>