我正在动态生成内容,所以我经常以documentFragments结束,我使用querySelectorAll或querySelector查询我在documentFragment中返回元素的nodeList.
我不时会在列表中添加一个项目,但我无法在网上找到关于这是否可行的任何内容.
我试过这样的:
- document.querySelectorAll(".translate").item(length+1) = document.createElement("div");
还有这个:
- document.querySelectorAll(".translate").shift(document.createElement("div"));
但两者都不起作用(如预期的那样)
题:
是否可以手动将元素添加到NodeList?我猜,不过还是要问.
感谢您的一些见解?
编辑:
更多信息:我正在生成一个动态内容块,我想将其附加到我的页面.默认情况下,该块为英文.由于用户正在用中文查看页面,我正在动态片段上运行翻译器,然后将其附加到DOM.在我的页面上,我还有一个元素,比如一个标题,它应该根据添加的动态内容而改变.我的想法是一步完成这个=尝试向我的nodeList添加一个元素.但是现在写它…我想不可能:-)
解决方法
编辑:正如@Sniffer所提到的,NodeLists是只读的(长度属性和项目).您可以操纵其他所有内容,如下所示,但如果您想要操作它们,最好将它们转换为数组.
- 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)).
- 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