When some html string added to DocumentFragment innerHTML property, there are no children exists. But same action with Element created by createElement show children. I created simple example for comparing innerHTML behavior for DocumentFragment and simple Element:
const fragment = document.createDocumentFragment();
const div = document.createElement('div')
fragment.innerHTML = "<i>Test</i>";
console.log('fragment children:', fragment.children); // empty
fragment.innerHTML = "<i><b>Test</b></i>";
console.log('fragment children:', fragment.children); // empty
div.innerHTML = "<i>Test</i>";
console.log('div children:', div.children) // has children
div.innerHTML = "<i><b>Test</b></i>";
console.log('div children:', div.children) // has children
But fragment can show children added by appendChild:
const span = document.createElement('span');
const fragment2 = document.createDocumentFragment();
fragment2.appendChild(span);
console.log('fragment children for appendChild', fragment2.children);
How to fix this weird DocumentFragment behavior ?
ADDITIONAL: I need DocumentFragment as temporary HTML container.
JSFiddle with reproducing the problem.
divinherits from theHTMLElementprototype, a child of theNodeprototypeDocumentFragmentinherits directly from theNodeprototype.This is to say that
divhas all of the Node methods and properties as well as all HTMLElement methods and properties.DocumentFragmentonly has Node methods and properties.Though the Node prototype has the ability to have children,
innerHTMLdoes not exist as an innate property. This is only available onHTMLElementand its children (in this caseHTMLDivElement).Assigning to
innerHTMLon a child of aNodeprototype simply creates the propertyinnerHTMLwith your string as a value, but does nothing more.Basically, elements have internal wiring that tells them what to
dowheninnerHTMLis assigned/updated. Nodes do not.You can see this below:
In order to use something as a
containerand utilizeinnerHTMLyou would really just need to create an element that contains what you're trying to add. You can use a number of different things like atemplateElement orDOMParser, but honestly the easiest is just to create a separatedivand classify it as acontainer