Phillip YS Phillip YS - 1 month ago 31
HTML Question

Uncaught DOMException: Failed to execute 'removeChild' on 'Node'


Failed to execute 'removeChild' on 'Node': The node to be removed is
not a child of this node.


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

Answer

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);
 }
}
Comments