How to Use innerHTML With JavaScript DocumentFragment Object?

Find out if there's a way to use innerHTML on DocumentFragment object in JavaScript

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;
console.log(fragment);

/*
Output:
    #document-fragment
        <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.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.