Using JavaScript insertBefore() to insert before a TextNode?

16,303

Solution 1

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

Solution 2

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.

Share:
16,303

Related videos on Youtube

Melissa Avery-Weir
Author by

Melissa Avery-Weir

.NET, Python/Django, HTML/JS/CSS, and Unity developer who enjoys a good bit of devops as well. Also a writer, knitter/crocheter, gamer, reader, and cook. I co-run Future Proof Games, an indie game company. We've released two games: Ossuary (written in AS3) and Exploit: Zero Day (written in TypeScript using Phaser). I'm a jack-of-all-trades for FPG: I do game design, biz dev, marketing, programming, accounting, devops -- my partner and I do everything. You can follow me on twitter, FPG on twitter, or read our dev blog.

Updated on April 29, 2022

Comments

  • Melissa Avery-Weir
    Melissa Avery-Weir almost 2 years

    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.

  • Melissa Avery-Weir
    Melissa Avery-Weir over 13 years
    Thank you, thank you. Your explanation helps a lot; I've mixed that up on appendChild, too, I think.
  • kermit
    kermit about 9 years
    I see - insertBefore must be called on the container/parent node which contains the node I want to insert before.