如何从两个或多个DOMNode创建NodeList对象 [英] How to create NodeList object from two or more DOMNodes

查看:341
本文介绍了如何从两个或多个DOMNode创建NodeList对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有两个DOMNode: let node1 = document.querySelector('#node-1'); let node2 = document.querySelector('#node-2');

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

如何将它们组合成NodeList对象?是否有像array.push(item)这样的简单解决方案?

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

推荐答案

您可以将两个节点都添加到文档片段中:

You can add both nodes into a document fragment:

var docFragment = document.createDocumentFragment();
docFragment.appendChild(node1);
docFragment.appendChild(node2);

如果您真的希望它们在NodeList中,请执行以下操作:

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.

这篇关于如何从两个或多个DOMNode创建NodeList对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆