Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 views
in Technique[技术] by (71.8m points)

dom - Using JavaScript insertBefore() to insert before a TextNode?

I have HTML like the following:

<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, 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>

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

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

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?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...