无法在"节点"上执行"insertBefore":插入新节点的节点不是此节点的子节点

bat*_*man 5 javascript xml

我正在尝试<name>在我的xml中的特定节点()之前插入注释节点.这是它的方法:

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
}
Run Code Online (Sandbox Code Playgroud)

当我打电话时:

test("<address><street><name>Street name</name></street></address>")
Run Code Online (Sandbox Code Playgroud)

我明白了:

<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)
Run Code Online (Sandbox Code Playgroud)

如您所见,<name>Street name</name>正确打印; 因为我想将comentDocument其附加到其父级<street>.

不知道我在哪里弄错了.

我期待代码返回:

<address>
   <street>
     <!-- My personal comments -->
     <name>Street name
     </name>
   </street>
</address>
Run Code Online (Sandbox Code Playgroud)

Bar*_*icz 5

xmlDoc.insertBefore( comentDocument ,  xmlDoc.querySelectorAll("street name")[0]);
Run Code Online (Sandbox Code Playgroud)

这尝试直接从文档插入。您需要先找到要插入评论的元素的直接父元素:

var name = xmlDoc.querySelector("street name");
name.parentNode.insertBefore(comentDocument, name);
Run Code Online (Sandbox Code Playgroud)