如何撤消“surroundContents”在 JavaScript 中?
我正在编写一个脚本,需要在页面上移动环绕节点元素。我发现当我这样做时,我移除了之前包裹的孩子。如何取消节点的子节点的嵌套,以便可以将该父节点移动到其他地方?
我在想这样的事情:
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”逻辑。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
insertBefore 对元素节点进行操作并采用两个参数,
新节点以及新节点之前的节点。
//测试
展开(document.getElementById("blah"));
insertBefore operates on an element node and takes two arguments,
the new node, and the node the new node will precede.
//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: