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>
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With