gpt4 book ai didi

javascript - InsertBefore 在 JavaScript 中不起作用

转载 作者:行者123 更新时间:2023-12-01 03:53:52 24 4
gpt4 key购买 nike

我已经厌倦了 insertBefore 属性,它会抛出脚本错误

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.

下面是我使用的代码。

            parent = document.getElementById(parentid[i]);
before = document.getElementById(beforeid[i]);
appenchild1 = document.getElementById(beforeid[i]);
appenchild2 = document.getElementById(appenchild2id[i]);
newnode = document.createElement("span");
newnode.className = "verticalHparent" + btncls[i];
newnode.style.display = "inherit";
parent.insertBefore(newnode, before);

insertBefore 方法抛出错误,有什么问题吗?

最佳答案

错误消息非常有解释性; before节点应该是 parent 的子节点代码上的节点。

这是一个工作示例(查看 html 结构):

<div id = "parent">

<div id = "child_1">child1</div>

</div>

<button onclick="createNewElement()">Create New Child</button>

<script type="text/javascript">

function createNewElement(){

var parent = document.getElementById("parent");
var before = document.getElementById("child_0");

var newnode = document.createElement("span");
newnode.className = "verticalHparent";
newnode.style.display = "inherit";
newnode.innerHTML = "child2";
parent.insertBefore(newnode, before);


}


</script>

关于javascript - InsertBefore 在 JavaScript 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42944031/

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