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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With