admin管理员组文章数量:1405516
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)
?
3 Answers
Reset to default 6You 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>
本文标签: javascriptHow to create NodeList object from two or more DOMNodesStack Overflow
版权声明:本文标题:javascript - How to create NodeList object from two or more DOMNodes - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744920915a2632286.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论