使用 JavaScript insertBefore() 在 TextNode 之前插入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3352871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 00:55:46  来源:igfitidea点击:

Using JavaScript insertBefore() to insert before a TextNode?

javascriptdom

提问by Melissa Avery-Weir

I have HTML like the following:

我有如下 HTML:

<div id="move-me">
    <a href="#">I'm a link</a>
</div>

<div id="new-parent">
    Some plain text.
</div>

I'm trying to write JavaScript that will move the entire #move-me div inside the #new-parent div, abovethe text, like so:

我正在尝试编写 JavaScript,将整个 #move-me div 移动到 #new-parent div 内,在文本上方,如下所示:

<div id="new-parent">
    <div id="move-me">
        <a href="#">I'm a link</a>
    </div>
    Some plain text.
</div>

Here's the JavaScript I have:

这是我拥有的 JavaScript:

function moveDiv() {
    var moveable = document.getElementById('move-me');
    var newParent = document.getElementById('new-parent');
    newParent.parentNode.insertBefore(moveable, newParent.firstChild);
}

I'm using Firebug to debug, and I can see that newParent.firstChildis a TextNode, but I always receive the following error:

我正在使用 Firebug 进行调试,我可以看到它newParent.firstChild是一个 TextNode,但是我总是收到以下错误:

Node was not found" code: "8
newParent.parentNode.insertBefore(moveable, newParent.firstChild); 

It seems like insertBeforerequires an element node and won't work on a text node... is that right? If so, is there another good method for doing this?

似乎insertBefore需要一个元素节点并且不能在文本节点上工作......是吗?如果是这样,是否有另一种好的方法来做到这一点?

Note: I can't modify or clean up the HTML to include paragraph tags or remove white space.

注意:我无法修改或清理 HTML 以包含段落标记或删除空格。

回答by Tim Down

No, insertBeforewill work fine with a text node as the node to be inserted before. The problem is that the node you're trying to insert before is not a child of the node you're inserting into. You need to remove the .parentNodebit:

不,insertBefore将文本节点作为要插入的节点正常工作。问题是您之前尝试插入的节点不是您要插入的节点的子节点。您需要删除该.parentNode位:

newParent.insertBefore(moveable, newParent.firstChild); 

回答by Scott M.

You need to remove the ".parentNode" from your insert statement. A text node is still a node and can be referenced like every other node.

您需要从插入语句中删除“.parentNode”。文本节点仍然是一个节点,可以像其他每个节点一样被引用。