2009-10-23 31 views
5

我正在写一个脚本,需要在页面上移动一个包裹节点元素。我发现当我这样做时,我将先前包裹的孩子删除。我如何打开一个节点的孩子,以便我可以在其他地方移动父节点?如何在JavaScript中撤消“surroundContents”?

我的想法是这样的:

var parg = document.getElementById("blah"); 

    if (parg.hasChildNodes()) 
    { 
    var children = parg.childNodes; 
    while (children.length > 0) 
    { 
     parg.insertBefore(parg.firstChild); 
     parg.removeChild(parg.firstChild); 
    }; 
    }; 

,我猜该生产线的问题了“的insertBefore”的逻辑。

+0

很好的问题!你真的很清楚地表达这个问题 – toddmo 2016-09-07 17:14:44

回答

7

的insertBefore元素节点上运行,并需要两个参数, 新节点,新节点将先于节点。

function unwrap(who){ 
var pa= who.parentNode; 
while(who.firstChild){ 
    pa.insertBefore(who.firstChild, who); 
} 
} 

//测试

解包(的document.getElementById( “嗒嗒”));

enter image description here

+0

这是一个绝妙的解决方案,谢谢。 – Matrym 2009-10-23 18:20:58

0

您需要迭代您的第一级子项并将其父项分配给“包装器”元素的父项。

事情是这样的,也许:

if (parg.hasChildNodes()) { 
    var children = parg.childNodes; 

    for (child in children) { 
     child.parentNode = parg.parentNode; 
    } 
}