代码之家  ›  专栏  ›  技术社区  ›  Matrym

如何撤消JavaScript中的“SurroundContents”?

  •  6
  • Matrym  · 技术社区  · 16 年前

    我正在编写一个脚本,需要在页面上移动包装节点元素。我发现当我这样做的时候,我会把以前裹好的孩子都带走。如何取消节点的子节点,以便将该父节点移到其他位置?

    我在想这样的事情:

      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”逻辑。

    2 回复  |  直到 9 年前
        1
  •  8
  •   toddmo    9 年前

    insertbefore在元素节点上操作并接受两个参数, 新节点和新节点将位于其前面的节点。

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

    /测试

    unwrap(document.getElementByID(“blah”));

    enter image description here

        2
  •  0
  •   Ryan Emerle    16 年前

    您需要迭代第一级子元素,并将它们的父元素分配给“wrapper”元素的父元素。

    可能是这样的:

    if ( parg.hasChildNodes() ) {
         var children = parg.childNodes;
    
         for ( child in children ) {
            child.parentNode = parg.parentNode;
         }
    }
    
    推荐文章