fre*_*ent 10 javascript arrays append nodelist
我正在动态生成内容,所以我经常最终会documentFragments
查询我在documentFragment中使用querySelectorAll
或querySelector
返回nodeList
的元素.
我不时会在列表中添加一个项目,但我无法在网上找到关于这是否可行的任何内容.
我试过这样的:
document.querySelectorAll(".translate").item(length+1) = document.createElement("div");
Run Code Online (Sandbox Code Playgroud)
还有这个:
document.querySelectorAll(".translate").shift(document.createElement("div"));
Run Code Online (Sandbox Code Playgroud)
但两者都不起作用(如预期的那样)
问题:
是否可以手动将元素添加到NodeList?我猜,不过还是要问.
感谢您的一些见解?
编辑:
更多信息:我正在生成一个动态内容块,我想附加到我的页面.默认情况下,该块为英文.由于用户正在用中文查看页面,我正在动态片段上运行翻译器,然后将其附加到DOM.在我的页面上,我还有一个元素,比如一个标题,它应该根据添加的动态内容而改变.我的想法是一步到位=尝试添加一个元素到我的nodeList
.但是现在写它...我想不可能:-)
Tib*_*bos 18
编辑:正如@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]);
}
}
Run Code Online (Sandbox Code Playgroud)
将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
Run Code Online (Sandbox Code Playgroud)
Ami*_*ati 11
我还有一个建议。您可以通过查询分隔符 ( ,
)选择多个节点,此代码将保存所有保存在节点变量中的 h2 和 h3 标签:
var nodes = document.querySelectorAll('h2, h3');
Run Code Online (Sandbox Code Playgroud)
与先前描述的元素选择方法不同,querySelectorAll()返回的NodeList不是活动的:它保存在调用方法时与选择器匹配的元素,但它不会随着文档的更改而更新.[1]
在NodeList
这种情况下是不是还活着,所以如果你添加/到/从它,那么它不会对文档结构的任何影响删除任何东西.
NodeList是一个只读数组对象.[1]
[1]: JavaScript:The Definitive Guid,David Flanagan