[英]How can I append an array of child nodes to a parent node in one operation using JavaScript?
In JavaScript, is there a way to add an array of child nodes to a parent node in one operation?在 JavaScript 中,有没有办法在一次操作中将一组子节点添加到父节点?
I want to do this in one operation to prevent unnecessary repaints.我想在一次操作中做到这一点,以防止不必要的重绘。
I have tried parent .appendChild(arrayOfNodes)
, but that gives an exception.我试过 parent .appendChild(arrayOfNodes)
,但这给出了一个例外。
I am making a small component that will be reused among several projects, I don't want to depend on any library like jQuery or Zepto.我正在制作一个将在多个项目中重复使用的小组件,我不想依赖任何库,如 jQuery 或 Zepto。
You could use an intermediate DocumentFragment
, which is a little convoluted but is likely to perform better than doing it a node at a time if you're appending newly-created nodes to an existing node within the document: 您可以使用中间DocumentFragment
,它有点复杂但如果您将新创建的节点附加到文档中的现有节点,则可能比一次执行一个节点更好:
var frag = document.createDocumentFragment();
for (var i = 0; i < arrayOfNodes.length; ++i) {
frag.appendChild(arrayOfNodes[i]);
}
someElement.appendChild(frag);
You could add a method to Node , which calls the appendChild method internally: 您可以向Node添加一个方法,该方法在内部调用appendChild方法:
(function () {
Node.prototype.appendChildren(arrayOfNodes) {
var length = arrayOfNodes.length;
for (var i = 0; i < length; i++) {
this.appendChild(arrayOfNodes[i]);
}
}());
Which would then be useable like so: 哪个可以这样使用:
node.appendChildren(arrayOfNodes)
I know this is kind of old but I had a similar question. 我知道这有点旧,但我有一个类似的问题。 I decided to write a simple function which takes a parent (node) and children nodes (nodeList or array of nodes), not extending any prototypes or making it any more complicated than I thought it needed to be... 我决定编写一个简单的函数,它接受一个父节点(节点)和子节点(nodeList或节点数组),不扩展任何原型或使它比我想象的更复杂......
function appendChildren(parent, children) {
for (var i=0; i<children.length;i++) {
child = children[i];
parent.appendChild(child);
}
return parent;
}
使用 ES6 扩展运算符,可以将 NodeList 附加到一行中的元素:
parent.append(...children);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.