最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

removechild - How do you undo "surroundContents" in javascript? - Stack Overflow

programmeradmin2浏览0评论

I'm writing a script that needs to move a wrapping node element around on the page. I find that when I do this, I remove the previously wrapped children. How do I unnest the children of a node, so that I can move that parent node elsewhere?

I was thinking something like this:

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

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

The line that I'm guessing is the problem is the "insertBefore" logic.

I'm writing a script that needs to move a wrapping node element around on the page. I find that when I do this, I remove the previously wrapped children. How do I unnest the children of a node, so that I can move that parent node elsewhere?

I was thinking something like this:

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

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

The line that I'm guessing is the problem is the "insertBefore" logic.

Share Improve this question edited Oct 23, 2009 at 17:12 Matrym asked Oct 23, 2009 at 16:48 MatrymMatrym 17.1k35 gold badges99 silver badges141 bronze badges 1
  • great question! You really express the problem clearly – toddmo Commented Sep 7, 2016 at 17:14
Add a ment  | 

2 Answers 2

Reset to default 8

insertBefore operates on an element node and takes two arguments, the new node, and the node the new node will precede.

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

//test

unwrap(document.getElementById("blah"));

You'll need to iterate over your first-level children and assign their parent to the "wrapper" element's parent.

Something like this, perhaps:

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

     for ( child in children ) {
        child.parentNode = parg.parentNode;
     }
}
发布评论

评论列表(0)

  1. 暂无评论