javascript 替换节点错误。要替换的节点不是该节点的子节点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21627276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replacing Nodes Error. The node to be replaced is not a child of this node
提问by J86
I can't see what I am doing wrong. I am getting a bunch of select lists (drop downs) and want to replace them with a <span>
, so here is my code:
我看不出我做错了什么。我得到了一堆选择列表(下拉列表)并想用 a 替换它们<span>
,所以这是我的代码:
var selectListElements = document.getElementsByTagName('SELECT');
//select elements
for (var i = 0; i < selectListElements.length; i++) {
var currentSelectList = selectListElements[i];
//alert(selectListElements[i].name);
if (currentSelectList.dontReplace != 'true') {
var newNode = document.createElement('SPAN');
var nodeText = currentSelectList.options[currentSelectList.selectedIndex].value;
var parentNode = currentSelectList.parentNode;
parentNode.replaceChild(currentSelectList, newNode);
i--;
newNode.innerText = nodeText;
newNode.className = 'tableBody';
newNode.style.verticalAlign = 'top';
}
}
But this is giving me the error:
但这给了我错误:
Uncaught NotFoundError: Failed to execute 'replaceChild' on 'Node': The node to be replaced is not a child of this node.
未捕获的 NotFoundError:无法在“节点”上执行“replaceChild”:要替换的节点不是该节点的子节点。
I can't see how that can be the case! I am grabbing the parent, so it must be a child!
我看不出怎么会这样!我在抓父母,所以它一定是一个孩子!
What am I doing wrong?
我究竟做错了什么?
回答by Eternal1
In replaceChild
, the new node is the first argument, not the second. You have them backwards.
在 中replaceChild
,新节点是第一个参数,而不是第二个参数。你让他们倒退。
parentNode.replaceChild(newNode, currentSelectList);
parentNode.replaceChild(newNode, currentSelectList);
Also, why would you do i--
? Isn't that creating an infinite loop?
还有,你为什么要这样做i--
?这不是在创建一个无限循环吗?