如何在现有父母和孩子之间插入DIV *? [英] How can I insert a DIV *between* an existing parent and child?
问题描述
假设我有一个带有父节点和一组子节点的部分dom树。
Suppose I have a partial dom tree with a parent node and a set of children.
如何在它们之间插入DIV?
How can I interject a DIV between them?
我开始于
parent --+--> child[0]
|--> child[1]
|--> child[2]
..我希望以
parent ---> newdiv ---+--> child[0]
|--> child[1]
|--> child[2]
我该怎么做?
我需要与 replaceChild()
相反。有没有类似 replaceParent()
?
I need the converse of replaceChild()
. Is there something like replaceParent()
?
我想我可以克隆所有子节点,然后插入它们作为新节点中的子节点。但是......是否保留了所有元素ID?
I suppose I could clone all the child nodes, and then insert them as children in the new node. but... does that retain all the element ids?
编辑 - 我没有用jQuery或任何框架标记这个,但也许我应该明确这一点。这不是一个jQuery问题。我想在javascript + DHTML中这样做。没有额外或外部框架。
EDIT - I didn't tag this with jQuery, or any framework, but maybe I should have been explicit about it. This is not a jQuery question. I want to do this in javascript + DHTML. No extra or outside framework.
推荐答案
您可以通过将元素附加到新父元素来移动元素。在普通的javascript中:
You can just move elements around by appending them to a new parent. In plain javascript:
var newDiv = document.createElement("div");
while(parent.hasChildNodes())
newDiv.appendChild(parent.firstChild);
parent.appendChild(newDiv);
来自 W3C的文档关于 appendChild
:
将节点newChild添加到此节点的子节点列表的末尾。如果newChild已经在树中,则首先将其删除。
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.
这篇关于如何在现有父母和孩子之间插入DIV *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!