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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With