Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: document.createElement('') & delete DOMElement

If you create a element within a function like:

function makeDomElement() {    var createdElement = document.createElement('textarea'); } 

And you do not append it anywhere in the DOM i.e. via .appendChild functions, does it still remain in memory? So would you have to do

function makeDomElement() {    var createdElement = document.createElement('textarea');    delete createdElement; } 

I'm just curious :)

like image 358
Gary Green Avatar asked Dec 04 '09 14:12

Gary Green


People also ask

What is document createElement in JavaScript?

The document. createElement() is used to dynamically create an HTML element node with the specified name via JavaScript. This method takes the name of the element as the parameter and creates that element node.

What does document createElement (' a ') return?

The document. createElement() accepts an HTML tag name and returns a new Node with the Element type.

What can you create with document createElement?

In an HTML document, the document. createElement() method creates the HTML element specified by tagName, or an HTMLUnknownElement if tagName isn't recognized.


2 Answers

It will vary from browser to browser however the javascript delete keyword has nothing to do with the DOM's createElement method. There is no need to use delete.

What will happen is that the reference to the element currently held in the createdElement will get garbage collected. Now in the case of IE that will mean that the element will have its reference count dropped to 0 so it will destroy itself and release its memory. Other browsers do things differently typically the elements in the DOM are themselves garbage collected objects and will be removed during the same (or perhaps a DOM specific) GC cycle.

Had the element been added to the document then in the case of IE there would be another reference added to the element so when the reference in createdElement is removed the element object would still have a non-zero reference count and continue to exist.

In the case of other browsers where the elements themselves are garbage collected the element wouldn't be collected since the collector would see it in the graph of objects connected to the document.

like image 105
AnthonyWJones Avatar answered Oct 04 '22 17:10

AnthonyWJones


After the function terminates, there's no longer any reference to the object, ie if the garbage collector works properly, it should be collected (there's an IE bug that prevents objects with circular references to be collected if DOM nodes are involved).

Also, your code is broken as local variables can't be deleted: trying to do so will even throw a syntax error in strict mode ES5.

like image 45
Christoph Avatar answered Oct 04 '22 16:10

Christoph