kongaraju
kongaraju

Reputation: 9596

insertAdjacentElement not accepting document fragment

I am trying to execute below snippet

let frag = document.createDocumentFragment();
let divElement = document.createElement('div');
    divElement.insertAdjacentElement('afterend', frag);

I am getting the below error.

Uncaught TypeError: Failed to execute 'insertAdjacentElement' on 'Element': parameter 2 is not of type 'Element'.

What is the restriction here? reference about error details would be much appreciated. Please suggest an alternative to do it efficiently.

Upvotes: 2

Views: 2492

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 371049

Fragments can be composed of multiple elements, not just single elements. In such a case, if the technique in your question worked, insertAdjacentElement would be inserting multiple elements, not just a single element. (It's not called insertAdjacentElements)

It just isn't allowed. Unlike appendChild, insertAdjacentElement can't take a fragment as an argument.

You could iterate through all children of the fragment and insert them afterend:

// Create fragment, append elements
const fragment = document.createDocumentFragment();
fragment.appendChild(document.createElement('span')).textContent = 'span1';
fragment.appendChild(document.createElement('span')).textContent = 'span2';
fragment.appendChild(document.createElement('span')).textContent = 'span3';


// First cast fragment.children from an HTMLCollection to an Array
// Since insertAdjacentElement will remove the element from fragment.children
// It will mutate on each loop causing issue
const childrenAsArray = Array.from(fragment.children);
// Iterate through fragment 
for (const element of childrenAsArray ) {
  divElement.insertAdjacentElement('beforeend', element);
}
<div id="divElement"></div>

Or you could call insertAdjacentElement directly instead of putting the elements into a fragment first.

Upvotes: 7

brk
brk

Reputation: 50326

createDocumentFragment is never part of main dom.In dom tree document fragment is replaced by its child. Also it cannot inherit from element base class. So it is not a valid element too. The syntax of insertAdjacentElement is targetElement.insertAdjacentElement(position, element) where element need to be a valid one as described by the above link.

Hence this error

Upvotes: 1

Related Questions