How to create NodeList object from two or more DOMNodes

馋奶兔 提交于 2019-12-25 07:00:48

问题


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)?


回答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.




回答2:


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




回答3:


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>


来源:https://stackoverflow.com/questions/35969843/how-to-create-nodelist-object-from-two-or-more-domnodes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!