是否可以将元素附加到 JavaScript 节点列表?
我正在动态生成内容,所以我经常以 documentFragments
结束,我正在使用 querySelectorAll
或 querySelector
进行查询返回我的 documentFragment 中元素的 nodeList
.
I'm generating content dynamically, so I'm often ending up with documentFragments
which I'm querying using querySelectorAll
or querySelector
returning a nodeList
of elements inside my documentFragment.
有时我想将一个项目添加到列表中,但我在网上找不到任何关于这是否可行的信息.
From time to time I would like to add an item to a list, but I can't find anything online on whether this is even possible.
我试过这样:
document.querySelectorAll(".translate").item(length+1) = document.createElement("div");
还有这个:
document.querySelectorAll(".translate").shift(document.createElement("div"));
但两者都不起作用(如预期)
But both don't work (as expected)
问题:
是否可以手动将元素添加到 NodeList?我猜,不是但还是问.
Question:
Is it possible to manually add elements to a NodeList? I guess, not but asking nevertheless.
感谢您提供一些见解?
编辑:
所以更多信息:我正在生成一个动态内容块,我想将其附加到我的页面.默认情况下,该块是英文的.由于用户正在查看中文页面,因此我在动态片段上运行翻译器,然后将其附加到 DOM.在我的页面上,我还有一个元素,比如标题,它应该根据添加的动态内容而改变.我的想法是一步完成 = 尝试向我的 nodeList
添加一个元素.但是从现在开始写...我想不可能:-)
EDIT:
So more info: I'm generating a block of dynamic content, which I want to append to my page. By default the block is in English. Since the user is viewing the page in Chinese, I'm running a translator on the dynamic fragment, BEFORE appending it to the DOM. On my page, I also have an element, say a title, which should change depending on the dynamic content being added. My idea was to do this in one step = try to add an element to my nodeList
. But from writing it now... I guess not possible :-)
推荐答案
正如@Sniffer 提到的,NodeLists 是只读的(长度属性和项目).您可以操作它们的所有其他内容,如下所示,但如果您想操作它们,最好将它们转换为数组.
As @Sniffer mentioned, NodeLists are read-only (both the length property and the items). You can manipulate everything else about them, like shown below, but it's probably better to convert them to arrays instead if you want to manipulate them.
var list = document.querySelectorAll('div');
var spans = document.querySelectorAll('span');
push(list, spans);
forEach(list, console.log); // all divs and spans on the page
function push(list, items) {
Array.prototype.push.apply(list, items);
list.length_ = list.length;
list.length_ += items.length;
}
function forEach(list, callback) {
for (var i=0; i<list.length_; i++) {
callback(list[i]);
}
}
将 NodeList 转换为数组可能会更好(list = Array.prototype.slice(list)
).
It would probably be a better idea to turn the NodeList to an array instead (list = Array.prototype.slice(list)
).
var list = Array.prototype.slice.call(document.querySelectorAll('div'));
var spans = Array.prototype.slice.call(document.querySelectorAll('span'));
list.push.apply(list, spans);
console.log(list); // array with all divs and spans on page
相关文章