65829
![Uncaught DOMException: Failed to execute 'removeChild' on 'Node' [duplicate]](https://www.xszz.org/skin/wt/rpic/t12.jpg)
Question:
This question already has an answer here:
<ul><li> <a href="/questions/750486/javascript-closure-inside-loops-simple-practical-example" dir="ltr" rel="nofollow">JavaScript closure inside loops – simple practical example</a> <span class="question-originals-answer-count"> 39 answers </span> </li> </ul> <blockquote>Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.
</blockquote>I'm getting the error when I execute this code below. Is there any ways to solve this problem?
function clickLinks(links) {
for(var item in links) {
var anchor = document.createElement("a");
anchor.target = "_blank";
anchor.href = links[item];
document.body.appendChild(anchor);
window.setTimeout(function() {
anchor.dispatchEvent(new MouseEvent("click",{
"bubbles" : true,
"cancelable" : true,
"view" : window
}));
window.setTimeout(function() {
document.body.removeChild(anchor);
}, 50);
}, 50);
}
}
Answer1:You need to create a closure for the anchor variable you are using in order to ensure that it is not overwritten in the next iteration of the for loop.
function clickLinks(links) {
for(var item in links) {
var anchor = document.createElement("a");
anchor.target = "_blank";
anchor.href = links[item];
document.body.appendChild(anchor);
(function iifeclosure(anchor){
window.setTimeout(function() {
anchor.dispatchEvent(new MouseEvent("click",{
"bubbles" : true,
"cancelable" : true,
"view" : window
}));
window.setTimeout(function() {
document.body.removeChild(anchor);
}, 50);
}, 50);
})(anchor);
}
}