开发者

How do you undo "surroundContents" in javascript?

开发者 https://www.devze.com 2022-12-09 20:18 出处:网络
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 th

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 pare开发者_运维问答nt 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.


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"));

How do you undo "surroundContents" in javascript?


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号