0

What happens to the div in this example? Do I have to delete it or clean it up?

var div = document.getElementById('myDiv');
var span = document.createElement('span');
span.textContent = 'hello world';
div.replaceWith(span);

Or is it garbage collected or something?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
whiterook6
  • 3,270
  • 3
  • 34
  • 77
  • What do you mean by `clean up`? Or by this question `Or is it garbage collected or something?` ? What exactly are you trying to do? – Ionut Necula Mar 27 '17 at 07:10
  • 1
    Like for any other object in js, it all depends on *do you keep an reference to it somewhere ?* The DOM itself will have lost its trace, so it would already be clean there, but you've to check that it's also clear on your side. – Kaiido Mar 27 '17 at 07:13
  • Didnt read into `replacewith` but the span might exist twice afterwards – efkah Mar 27 '17 at 07:31

1 Answers1

2

Assuming you release your reference to it once you're done, it's garbage collected; there's no explicit "delete" or similar in the DOM.

So at the end of your code, if the div variable isn't going out of scope or is being retained by a closure, you'll want to do

div = undefined;

...to make sure you don't retain a reference to the div. But if it's going out of scope and isn't retained by a closure, that's not necessary.


Side note: The DOM's replaceWith is quite new and support for it may be spotty.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thanks! I knew the variable would go out of scope but wasn't sure if all these elements would hang around in some sort of pool or something. – whiterook6 Mar 27 '17 at 14:34