KevBot KevBot -4 years ago 198
Javascript Question

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

. 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

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


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

Answer Source

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 )
<script src=""></script>

  <tr id=Row></tr>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download