4

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

1 Answers1

2

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);
 }
}
Travis J
  • 81,153
  • 41
  • 202
  • 273