首先要做的事情是:这不是问如何将 NodeList 转换为 Array。这是相反的。
为了一致性,我想创建一个返回 NodeList 的函数,就像document.querySelectorAll()做的那样。
这是我当前的代码:
var toNodeList = function(arrayOfNodes){
var fragment = document.createDocumentFragment();
arrayOfNodes.forEach(function(item){
fragment.appendChild(item);
});
return fragment.childNodes;
};
Run Code Online (Sandbox Code Playgroud)
然而,这会从 DOM 中删除原始元素!
我怎样才能NodeList以非破坏性的方式制作一个?
您需要克隆该节点。
var toNodeList = function(arrayOfNodes){
var fragment = document.createDocumentFragment();
arrayOfNodes.forEach(function(item){
fragment.appendChild(item.cloneNode());
});
return fragment.childNodes;
};
Run Code Online (Sandbox Code Playgroud)
注意传递true到cloneNode以进行深度克隆。