例如,我有两个 DOMNode:
let node1 = document.querySelector('#node-1');
let node2 = document.querySelector('#node-2');
如何将它们组合成 NodeList 对象?有没有简单的解决方案array.push(item)
?
例如,我有两个 DOMNode:
let node1 = document.querySelector('#node-1');
let node2 = document.querySelector('#node-2');
如何将它们组合成 NodeList 对象?有没有简单的解决方案array.push(item)
?
您可以将两个节点都添加到文档片段中:
var docFragment = document.createDocumentFragment();
docFragment.appendChild(node1);
docFragment.appendChild(node2);
如果您真的希望它们在 NodeList 中,请执行以下操作:
var list = docFragment.querySelectorAll('*');
不利的一面是,只要将节点附加到文档片段,就会将它们从实际文档中删除。
将此视为对 Orr Siloni 答案的补充:
如果我们不希望节点从 DOM 中移除,我们可以使用node.cloneNode()
.
var nList = document.querySelectorAll('[id^="node"]');
收集 id 以“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>