使用JavaScript insertBefore()在TextNode之前插入? [英] Using JavaScript insertBefore() to insert before a TextNode?
问题描述
我有如下的HTML:
<div id="move-me">
<a href="#">I'm a link</a>
</div>
<div id="new-parent">
Some plain text.
</div>
我正在尝试编写JavaScript,将移动整个#move-me div在#new -parent div,以上文本,如下所示:
I'm trying to write JavaScript that will move the entire #move-me div inside the #new-parent div, above the text, like so:
<div id="new-parent">
<div id="move-me">
<a href="#">I'm a link</a>
</div>
Some plain text.
</div>
这是我有的JavaScript:
Here's the JavaScript I have:
function moveDiv() {
var moveable = document.getElementById('move-me');
var newParent = document.getElementById('new-parent');
newParent.parentNode.insertBefore(moveable, newParent.firstChild);
}
我正在使用Firebug进行调试,我可以看到 newParent.firstChild
是一个TextNode,但我总是收到以下错误:
I'm using Firebug to debug, and I can see that newParent.firstChild
is a TextNode, but I always receive the following error:
Node was not found" code: "8
newParent.parentNode.insertBefore(moveable, newParent.firstChild);
似乎 insertBefore
需要一个元素节点并且不会在文本节点上工作...是对的吗?如果是这样,还有另一个好办法吗?
It seems like insertBefore
requires an element node and won't work on a text node... is that right? If so, is there another good method for doing this?
注意:我无法修改或清理HTML以包含段落标签或删除空格。
Note: I can't modify or clean up the HTML to include paragraph tags or remove white space.
推荐答案
不, insertBefore
将正常工作文本节点作为要插入的节点。问题是您之前尝试插入的节点不是要插入的节点的子节点。您需要删除 .parentNode
位:
No, insertBefore
will 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 .parentNode
bit:
newParent.insertBefore(moveable, newParent.firstChild);
这篇关于使用JavaScript insertBefore()在TextNode之前插入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!