Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert an Array of elements into a NodeList?

Tags:

javascript

dom

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?

like image 585
mikemaccana Avatar asked Jul 21 '14 16:07

mikemaccana


1 Answers

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.

like image 189
Dominic Avatar answered Sep 28 '22 11:09

Dominic