tHTML: handle mixed text/element nodes in top level

This commit is contained in:
tophf 2017-08-18 17:00:06 +03:00
parent 6625cd4349
commit 21b2ba572b

View File

@ -23,7 +23,8 @@ function tHTML(html, tag) {
return document.createTextNode(html); return document.createTextNode(html);
} }
if (typeof html === 'string') { if (typeof html === 'string') {
html = html.replace(/>\s+</g, '><'); // spaces are removed; use &nbsp; for an explicit space // spaces are removed; use &nbsp; for an explicit space
html = html.replace(/>\s+</g, '><').trim();
if (tag) { if (tag) {
html = `<${tag}>${html}</${tag}>`; html = `<${tag}>${html}</${tag}>`;
} }
@ -31,13 +32,13 @@ function tHTML(html, tag) {
if (html.includes('i18n-')) { if (html.includes('i18n-')) {
tNodeList(body.getElementsByTagName('*')); tNodeList(body.getElementsByTagName('*'));
} }
// the html string may contain more than one top-level elements // the html string may contain more than one top-level node
if (body.childElementCount <= 1) { if (!body.childNodes[1]) {
return body.firstElementChild; return body.firstChild;
} }
const fragment = document.createDocumentFragment(); const fragment = document.createDocumentFragment();
while (body.childElementCount) { while (body.firstChild) {
fragment.appendChild(body.firstElementChild); fragment.appendChild(body.firstChild);
} }
return fragment; return fragment;
} }