0

I have a JS-created text node var node = document.createTextNode(null) that I'm binding custom events to:

node.addEventListener('customEvent', function(){
  console.log('hi');
}, false);
node.dispatch('customEvent');

Once I'm done, I'd like to cleanly remove the node + the event listeners.

Read here that the simplest way to do that (not having to keep a reference to the callback because I have several), is to remove the node itself.

To do that, the method is node.parentNode.removeChild(node);.

Fine, but in my case node.parentNode is null.

How do I do?

I tried document.removeChild(node); as I thought the actual parent would be document, but I get: Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.

Community
  • 1
  • 1
Augustin Riedinger
  • 20,909
  • 29
  • 133
  • 206

1 Answers1

0

If you've created the node but never attached it to a document, all that's necessary to release it and the things it refers to (its event handlers) is to release all references to it. In your case, if node is the only thing that references it, then:

node = null; // or undefined, or 42, doesn't matter
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875