How to Use innerHTML With JavaScript DocumentFragment Object?

Using innerHTML property on a DocumentFragment object is not possible because the innerHTML property does not exist on the DocumentFragment object. If you need to parse a string containing HTML tags and get it as a DocumentFragment object, then you can make use of the <template> tag in the following way instead:

const str = '<p>hello world!</p>';

const tpl = document.createElement('template');
tpl.innerHTML = str;

const fragment = tpl.content;

        <p>hello world!</p>

The reason this works is because the <template> element supports innerHTML property, and has a content property that returns a DocumentFragment containing <template> element's contents (which in this case are the parsed HTML tags from our string).

Using DocumentFragment.appendChild() or DocumentFragment.insertBefore() won't be of much use in this case as either of those don't parse string HTML tags.

Be aware that the DocumentFragment will strip out <html>, <head> and <body> tags if they exist in the string. If you wish to have those included then you should consider using DOMParser.parseFromString() instead.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.