admin管理员组文章数量:1425104
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
本文标签: javascriptinsertAdjacentElement not accepting document fragmentStack Overflow
版权声明:本文标题:javascript - insertAdjacentElement not accepting document fragment - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745381931a2656204.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论