4

when I append an element and afterwards remove it the object still exists?

bg = $('<div class="dialog_bg"></div>');
$('#'+elm).append(bg);

bg.remove();

how is that? isn't it possible to remove the element permanently?

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
clarkk
  • 27,151
  • 72
  • 200
  • 340
  • 2
    your code should remove the element from the DOM. The element still exists in the variable "bg" but not in the DOM. You can set bg = null; so the JS garbage collector will delete it. If the element isn't removed from the DOM then something else is wrong with your code.. – sled May 10 '11 at 21:47
  • it looks like the element is removed from the DOM.. but if I put the object "bg" in a if-statement it returns true – clarkk May 10 '11 at 21:55
  • how can I then in jQuery check if the element has been removed? – clarkk May 10 '11 at 21:56
  • There might be a different way, but you can use the `has()` method. Try `$("html").has(bg)` - if the returned object has length 0, then it's not on the page. So, `if ($("html").has(bg).length == 0)` says if it's not there. – Tesserex May 10 '11 at 22:00
  • is this the only and fastest way to do it? – clarkk May 10 '11 at 22:06

3 Answers3

2

The remove method just takes the object out of the DOM, in other words, takes it off the page. Are you asking about deleting the object from memory? In that case, I don't think you can do it yourself explicitly - why do you need to? Javascript is a garbage collected language.

edit: also see this question for more information.

Community
  • 1
  • 1
Tesserex
  • 17,166
  • 5
  • 66
  • 106
  • ok.. but how can I then check (in jquery) if the object has a "link" to the DOM? – clarkk May 10 '11 at 21:52
  • You need to remove all references to that node to allow [garbage collector](http://stackoverflow.com/questions/864516/what-is-javascript-garbage-collection) to do his job releasing it from the memory. – Nik Sumeiko May 03 '14 at 16:14
2

so the element is removed from the DOM completely. That's fine. Your question is how to ensure that the element is really removed.

I'd use the .parent() method for that. Because if the element is removed from the DOM it won't have a parent anymore. This may be faster than $("html").has(bg) because it doesn't have to traverse the whole DOM Tree.

bg = $('<div class="dialog_bg"></div>');
$('#'+elm).append(bg);

bg.remove();

if(bg.parent().length == 0) {
   // removed succesfully
} else {
   // still somewhere in the dom
}

// tells the garbage collector to free the memory because there's no way to access the element anymore
bg = null;
sled
  • 14,525
  • 3
  • 42
  • 70
  • 1
    ok.. but isn't there a method to do both? both removing the element from the DOM and then setting the variable to NULL (freeing memory)? – clarkk May 11 '11 at 08:57
-1

How about:

$('div.dialog_bg').remove();

You might have added something inside the div so it's not recognizing it anymore.

kei
  • 20,157
  • 2
  • 35
  • 62