Search code examples
javascripttemplateshtml-parsingdomparser

DomParser parseFromString removing nodes


I came across some strange behaviour when using the DomParser. It appears that if the first element is a TEMPLATE, it's ignored.

See the output of below:

printTags('<template></template><h1></h1>', 'text/html');
document.write('<hr>')
printTags('<h1></h1><template></template>', 'text/html');

function printTags(str)
{
	let doc = new DOMParser().parseFromString(str, 'text/html');
	document.write(Array.from(doc.body.children).map(child => child.tagName).join(','));
}

Browser: Chrome 72

Is this usual behaviour? If so, where can I find the documentation?


Solution

  • DOMParser() parse HTML source code from the string into a DOM. It's not sure that string contents parsed as body, so try wrapping it with <body> tag.

    printTags('<body><template></template><h1></h1></body>', 'text/html');
    document.write('<hr>')
    printTags('<body><h1></h1><template></template></body>', 'text/html');
    
    function printTags(str) {
      let doc = new DOMParser().parseFromString(str, 'text/html');
      document.write(Array.from(doc.body.children).map(child => child.tagName).join(','));
    }