javascript - How to create NodeList object from two or more DOMNodes - Stack Overflow

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

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

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

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

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

Share Improve this question asked Mar 13, 2016 at 11:47 MihailMihail 6185 silver badges16 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

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.

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().

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);
}
<div id="node-1">node-1</div>
<div id="node-2">node-2</div>
<div id="notnode-3">notnode-3</div>
<div id="check">Check the console (F12, then choose the 'console' tab)</div>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744920915a4601125.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信