insertAdjacentElement 不接受文档片段

Kon*_*aju 2 javascript dom

我正在尝试执行下面的代码片段

let frag = document.createDocumentFragment();
let divElement = document.createElement('div');
    divElement.insertAdjacentElement('afterend', frag);
Run Code Online (Sandbox Code Playgroud)

我收到以下错误。

未捕获类型错误:无法在“Element”上执行“insertAdjacentElement”:参数 2 不是“Element”类型。

这里有什么限制呢?有关错误详细信息的参考将不胜感激。请提出一种有效的替代方案。

Cer*_*nce 7

片段可以由多个元素组成,而不仅仅是单个元素。在这种情况下,如果您问题中的技术有效,insertAdjacentElement则将插入多个元素,而不仅仅是单个元素。(这不是叫insertAdjacentElements

这是不允许的。与 不同的是appendChildinsertAdjacentElement不能将片段作为参数。

您可以迭代片段的所有子级并插入它们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);
}
Run Code Online (Sandbox Code Playgroud)
<div id="divElement"></div>
Run Code Online (Sandbox Code Playgroud)

或者您可以insertAdjacentElement直接调用,而不是先将元素放入片段中。