如何将一组元素转换为NodeList? [英] How can I convert an Array of elements into a NodeList?
本文介绍了如何将一组元素转换为NodeList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
document.querySelectorAll()一样, / code>。
以下是我当前的代码:
var toNodeList = function(arrayOfNodes ){
var fragment = document.createDocumentFragment();
arrayOfNodes.forEach(function(item){
fragment.appendChild(item);
});
return fragment.childNodes;
};
但是,这会从DOM中删除原始元素!
如何以非破坏性方式制作 NodeList
?
解决方案您需要克隆该节点。
var toNodeList = function(arrayOfNodes){
var fragment = document.createDocumentFragment();
arrayOfNodes.forEach(function(item){
fragment.appendChild(item.cloneNode());
});
return fragment.childNodes;
};
注意通过 true
至 cloneNode
做一个深层克隆。
First things first: this isn't asking to how to turn a NodeList into an Array. This is the opposite.
For consistency's sake, I would like to create a function that returns a NodeList, just like document.querySelectorAll()
does.
Here's my current code:
var toNodeList = function(arrayOfNodes){
var fragment = document.createDocumentFragment();
arrayOfNodes.forEach(function(item){
fragment.appendChild(item);
});
return fragment.childNodes;
};
However this removes the original elements from the DOM!
How can I make a NodeList
in a non-destructive fashion?
解决方案 You would need to clone the node.
var toNodeList = function(arrayOfNodes){
var fragment = document.createDocumentFragment();
arrayOfNodes.forEach(function(item){
fragment.appendChild(item.cloneNode());
});
return fragment.childNodes;
};
Note pass true
to cloneNode
to make a deep clone.
这篇关于如何将一组元素转换为NodeList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文