Search code examples
javascripthtmldocumentfragmenthtml5-template

In DocumentFragment: Failed to execute 'insertAdjacentHTML' on 'Element': The element has no parent


I am working inside of a DocumentFragment, and am attempting to insert HTML into it. We know that that a DocumentFragment does not have an innerHTML setter, so I attempted to insert a temporary node into the DocumentFragment and insert HTML after it using insertAdjacentHTML. I would then remove the temporary element, and be left with a fragment with the DOM I wanted.

Example: (error is on purpose)

var fragment = document.createDocumentFragment();
var temporaryElement = fragment.appendChild(document.createElement('div'));

// Before we move on.. I can see that the `temporaryElement` does have a parent
console.log(temporaryElement.parentNode.nodeType);

// The following throws an error...
temporaryElement.insertAdjacentHTML('afterend', '<div>Some crazy custom HTML..</div>');

fragment.removeChild(temporaryElement);

I can clearly see that there is a parentNode for the temporary element, so why would I get this error?


Solution

  • You can:

    1. Create a <template> element,
    2. Add string content via its innerHTML property,
    3. Get a DocumentFragment from its content property.

    //Use a template
    var template = document.createElement( 'template' )
    template.innerHTML = '<td>Hello<td>World'
    
    //Get the document fragment
    var fragment = template.content
    Row.appendChild( fragment )
    <table>
      <tr id=Row></tr>
    </table>