I am trying to execute below snippet
let frag = document.createDocumentFragment();
let divElement = document.createElement('div');
divElement.insertAdjacentElement('afterend', frag);
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.
Share Improve this question asked May 3, 2020 at 14:18 kongarajukongaraju 9,62611 gold badges59 silver badges78 bronze badges2 Answers
Reset to default 7Fragments can be posed 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.
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
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745381931a4625268.html
评论列表(0条)