How do you undo “surroundContents” in javascript?
-
06-07-2019 - |
Question
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.
OTHER TIPS
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;
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow