Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node

Tags:

javascript

xml

I'm trying to insert a comment node before the particular node (<name>) in my xml. Here is the method for it:

function test(xmlResponse)
{
    var parser = new DOMParser(), xmlDoc = parser.parseFromString(xmlResponse,"text/xml");

    var comentDocument = document.createComment("My personal comments");

    console.log(xmlDoc.querySelectorAll("street name")[0])
    xmlDoc.insertBefore( comentDocument ,  xmlDoc.querySelectorAll("street name")[0]);

    return xmlDoc
}

and when I call:

test("<address><street><name>Street name</name></street></address>")

I get:

<name>Street name</name>
Uncaught DOMException: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.
    at Error (native)
    at generateTheComment (<anonymous>:12:9)
    at <anonymous>:2:1
    at Object.InjectedScript._evaluateOn (<anonymous>:895:140)
    at Object.InjectedScript._evaluateAndWrap (<anonymous>:828:34)
    at Object.InjectedScript.evaluate (<anonymous>:694:21)

As you can see the <name>Street name</name> is getting printed correctly; as I want to append the comentDocument to its parent <street>.

Not sure where I'm making mistake here.

I'm expecting the code to return back:

<address>
   <street>
     <!-- My personal comments -->
     <name>Street name
     </name>
   </street>
</address>
like image 877
batman Avatar asked Jun 18 '15 10:06

batman


1 Answers

xmlDoc.insertBefore( comentDocument ,  xmlDoc.querySelectorAll("street name")[0]);

This tries to insert directly from the document. You need to get to the direct parent of the element you want to insert your comment before:

var name = xmlDoc.querySelector("street name");
name.parentNode.insertBefore(comentDocument, name);
like image 159
Bartek Banachewicz Avatar answered Oct 29 '22 12:10

Bartek Banachewicz