Skip to content
Advertisement

Why does insertBefore delete the reference node here?

Edit: Found the problem somewhere else, sorry, false alarm!

I can’t seem to figure out why insertBefore() is deleting the reference object in this javascript function:

function InsertItem(xml, newXml){
    var root =  xml.getElementsByTagName("root")[0];
    console.log("before: " + XmlToString(xml));
    root.insertBefore(newXml.childNodes[0], root.firstChild);
    console.log("after: " + XmlToString(xml));

    return xml;
}

The console shows a node being present before insertBefore is executed, but it is somehow deleted and replaced by the new node afterwards. Everything still works perfectly fine after this, except for the fact that I’m missing the old node.

For some reason I can’t get any variation I can think of to work, either the reference is deleted or I receive error messages.

Extra info:

‘xml’ is a variable containing an xml structure like:

<root>
     <item>
        ...
     </item>
<root>

And newXml contains a structure like:

<item>
   ...
</item>

Both xml and newXml were parsed from valid xml strings using:

( new window.DOMParser() ).parseFromString(string, "text/xml"); 

Advertisement

Answer

I’d say post the rest of your code. JSFiddle showing your code working

 before: <root><item>old</item></root>
 after: <root><item>insert</item><item>old</item></root>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement