javascriptdom

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


First thing's 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?


Solution

  • 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.