-1

This is different from Remove dom element without knowing its parent?, because their element does have a parentNode.

I know how to remove an element through its parentNode, but if I create a new element, it doesn't have a parentNode at all.

So,
a) How can I remove this element?
b) Do I even need to? Or is it cleaned up as soon as the last reference to it is gone?

The context: I'm trying to write some automated tests for my JavaScript code. I'm using Mocha from the browser, and I want to test if child elements are inserted into a given parent. I create the parent on the fly before each test, but thought I shouldn't have to add it to the document. But I want to make sure that I got no big list of unreferenced nodes hanging around.

var element = document.createElement('div');

console.log(element); // The div

console.log(element.parentNode); // null

element.parentNode.removeChild(element); // "Cannot read property 'removeChild' of null"
GolezTrol
  • 114,394
  • 18
  • 182
  • 210
  • 2
    As long as the element is not attached to any document, it’s basically little more than a plain JS object. You can discard it with `element = null;`. – Boldewyn Feb 04 '16 at 13:10
  • 1
    there should be a `batman()` function for that – online Thomas Feb 04 '16 at 13:10
  • @Boldewyn That's what I suspected, but I couldn't find proof. I thought maybe because it was created through document.CreateElement that it was also added somewhere in a list of elements of the document. – GolezTrol Feb 04 '16 at 13:12
  • Why this - `element.parentNode.removeChild(element);` instead of just `element.remove()`? – Al.G. Feb 04 '16 at 13:12
  • @Al.G. Browser support on element.remove() is quite poor atm. – GolezTrol Feb 04 '16 at 13:13

2 Answers2

1

what did you mean by "remove" it. When it has a parent node that means you append it in DOM. You remove it means you remove it from DOM. Since you didn't append it at all, it is just

  "<div></div>"

, if you log this element. All you have to do is:

  element = null;

or not do anything.

jilykate
  • 5,430
  • 2
  • 17
  • 26
0

Whilst the element hasn't been added to the DOM it's no different to any other Javascript object and will be garbage collected as soon as the last reference is gone.

Either overwrite the reference or just wait for it to go out of scope.

Dan Prince
  • 29,491
  • 13
  • 89
  • 120