Kokodoko
Kokodoko

Reputation: 28148

How to clear DOM elements created with jQuery from memory?

My app is using jQuery to add lots of DOM elements on the fly. All these elements are put into a main container div.

Then, every time a new page is shown, this container div is removed using jQuery's remove(); The problem is, it seems that all the children of this container div still seem to be listed under "Nodes" in Chrome's devtools timeline.

The longer I run my app, the more DOM elements I'm creating! But when looking at the HTML source, the nodes aren't there.

Detached elements

My code:

    // creating lots of jquery elements and appending them to maincontainer
    var elm = document.createElement("DIV");
    var jq = jQuery(elm).text("hello");
    maincontainer.append(jq);

    // then, the main container(also a jquery object) is removed using
    maincontainer.remove();

What is wrong with clearing DOM nodes from memory this way? Why are they retained under "nodes"?

Upvotes: 3

Views: 6318

Answers (3)

Ashok Jangid
Ashok Jangid

Reputation: 36

Always use:

$("ElementName").detach()

When you want to remove an element from DOM, it will not increase Memory of DOM and browser will not be stuck.

Upvotes: 1

Raptus
Raptus

Reputation: 495

I would pressume, it is still stored under nodes because you've reserved that element in a variable, forever making it accessible.

So it will reserve...

var elm = document.createElement("div");

Because that variable may be accessed again to do anything you wish to do with it, like add it back into the page and so forth.

Edit: Also if you want to 'clear' variables from stack, or in your terms 'memory' you might want to consider creating the variable under a local scope... e.g.

<button type="button" id="btn-example">Click me!</button>

$(document).on("click", "#btn-example", function() {
  var elm = $('div');
  elm.remove();
});

or in raw JS...

<button type="button" onclick="removeDiv();">Click me!</button>

function removeDiv() {
  var elm = document.getElementByTagName('div');
  elm.parentNode.removeChild(elm);
}

This is because local variables are created when the function is activated, then destroyed when the function ceases.

Upvotes: 2

Soundar
Soundar

Reputation: 2589

After removing the elements from page, just clear the variables also.. so the elements which are stored internally also gets cleaned.. If the element is stored in divElements variable,

divElements.remove();
divElements = null;

I don't know it may a solution for you... but it works in my application..

Upvotes: 3

Related Questions