gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 01:57:57 61 4
gpt4 key购买 nike

我试图在我的 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/

61 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com