注意:在假设此问题重复之前,此问题底部有一个部分解决了为什么一些类似的问题无法提供我正在寻找的答案.
我们都知道将NodeList转换为数组很容易,有很多方法可以做到:
[].slice.call(someNodeList)
// or
Array.from(someNodeList)
// etc...
Run Code Online (Sandbox Code Playgroud)
我所追求的是相反的; 如何将节点数组转换为静态NodeList?
在没有深入研究的情况下,我正在创建一种新方法来查询页面上的元素,即:
Document.prototype.customQueryMethod = function (...args) {...}
Run Code Online (Sandbox Code Playgroud)
为了坚持如何querySelectorAll工作,我想要返回静态集合NodeList而不是数组.
到目前为止,我已经以三种不同的方式解决了这个问题:
function createNodeList(arrayOfNodes) {
let fragment = document.createDocumentFragment();
arrayOfNodes.forEach((node) => {
fragment.appendChild(node);
});
return fragment.childNodes;
}
Run Code Online (Sandbox Code Playgroud)
虽然这确实返回了NodeList,但这不起作用,因为调用appendChild会从DOM中的当前位置(它应该保留的位置)中移除节点.
另一种变化涉及cloning节点并返回克隆.但是,现在您将返回克隆节点,这些节点没有引用DOM中的实际节点.
const FakeNodeList = (() => {
let fragment = document.createDocumentFragment();
fragment.appendChild(document.createComment('create a nodelist'));
function NodeList(nodes) {
let scope = this;
nodes.forEach((node, i) => {
scope[i] = node;
});
}
NodeList.prototype = …Run Code Online (Sandbox Code Playgroud)