Skip to content Skip to sidebar Skip to footer

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 th

Solution 1:

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.

Solution 2:

var nList = document.querySelectorAll('[id^="node"]');

Collect all nodes with an id that starts with "node".

var nList = document.querySelectorAll('[id^="node"]');
for (var i = 0; i < nList.length; i++) {
  var node = nList[i].id;
  console.log('Node: ' + node);
}
<divid="node-1">node-1</div><divid="node-2">node-2</div><divid="notnode-3">notnode-3</div><divid="check">Check the console (F12, then choose the 'console' tab)</div>

Solution 3:

Consider this as an addition to Orr Siloni's answer:

If we don't want the node to be removed from the DOM, we can append a copy of the node using node.cloneNode().

Post a Comment for "How To Create Nodelist Object From Two Or More Domnodes"