javascriptdomdom-node

How to create NodeList object from two or more DOMNodes


For example I have two DOMNodes: let node1 = document.querySelector('#node-1'); let node2 = document.querySelector('#node-2');

How do I combine them into a NodeList object? Is there an easy solution like array.push(item)?


Solution

  • You can add both nodes into a document fragment:

    var docFragment = document.createDocumentFragment();
    docFragment.appendChild(node1);
    docFragment.appendChild(node2);
    

    And if you really want them in a NodeList do:

    var list = docFragment.querySelectorAll('*');
    

    The down side to this is that as soon as you append the nodes to the document fragment you remove them from the actual document.