假设我有一个带有父节点和一组子节点的部分 dom 树。
如何在它们之间插入 DIV?
我开始
parent --+--> child[0]
|--> child[1]
|--> child[2]
..我想结束
parent ---> newdiv ---+--> child[0]
|--> child[1]
|--> child[2]
我该怎么做?
我需要 replaceChild()
的逆向。是否有类似 replaceParent()
的东西?
我想我可以克隆所有子节点,然后将它们作为子节点插入到新节点中。但是......那会保留所有元素ID吗?
编辑 - 我没有用 jQuery 或任何框架标记它,但也许我应该明确说明。这不是 jQuery 问题。我想在 javascript + DHTML 中执行此操作。没有额外的或外部的框架。
最佳答案
您可以通过将元素附加到新的父级来移动元素。在普通的 JavaScript 中:
var newDiv = document.createElement("div");
while(parent.hasChildNodes())
newDiv.appendChild(parent.firstChild);
parent.appendChild(newDiv);
来自documentation of W3C关于 appendChild
:
Adds the node newChild to the end of the list of children of this node. If the newChild is already in the tree, it is first removed.
关于javascript - 我怎样才能在现有的 parent 和 child 之间插入一个 DIV *?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7700140/