javascript - 无法在 'insertBefore' : The node before which the new node is to be inserted is not a child of this node 上执行 'Node'

标签 javascript xml

我试图在我的 xml 中的特定节点 ( <name> ) 之前插入一个注释节点。这是它的方法:

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
}

当我打电话时:

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

我得到:

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

如您所见<name>Street name</name>打印正确;因为我想附加 comentDocument到它的 parent <street> .

不确定我在哪里犯了错误。

我期待代码返回:

<address>
   <street>
     <!-- My personal comments -->
     <name>Street name
     </name>
   </street>
</address>

最佳答案

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

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

var name = xmlDoc.querySelector("street name");
name.parentNode.insertBefore(comentDocument, name);

关于javascript - 无法在 'insertBefore' : The node before which the new node is to be inserted is not a child of this node 上执行 'Node',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30913032/

相关文章:

javascript - 映射返回返回递归的最后一次迭代?

c# - XML 解析错误 - 使用 C# 的 Salesforce 批量 API

xml - 在 ISS-UI AATS 2016 网站上寻找示例 IRS AIR XML 文件

xml - 使用 Delphi7 TClientDataSet : is it possible to have it save its XML contents in an indented format?

c# - 如何通过提供 XML 源文件作为输入来创建组件

javascript - 获取没有输入标签的 Td 内部 html - Jquery

javascript - 并排显示两个外部网页的最佳方式是什么?

javascript - 返回 jQuery 点击函数 css 变回

java - 内部包含尖括号的正则表达式 XML 标签

javascript - 在编译时检测不受支持的正则表达式功能