I have a button click event that grabs names associated with checkboxes that are checked and adds them to a <ul> with checkboxes on the right side of the page. This works fine I then have another button that will remove and <li>‘s with checked checkboxes from the <ul>. This works to. The problem comes when you go to add back an item that has been deleted from the right side. The item is not on the page, so it obviously removed from the DOM, but it’s as if it’s stored in browser memory still. How do I go about clearing it out of memory? Code is below.
$('.add-people').click(function () {
$('.add-names:checked').each(function () {
var name = $(this).parent().siblings('td.name-cell').html();
if ($('ul.group-list').find(':contains(' + name + ')').length) {
//Name is already in list
} else {
var newLi = '<li><input id="name" class="remove-names" type="checkbox" name="' + name + '"><span>' + name + '</span></li>'
$('ul.group-list').append(newLi);
}
});
});
$('.remove-people').click(function () {
$('.remove-names:checked').each(function () {
$(this).parent().remove();
});
});
Once a DOM element is removed from the DOM, it is only kept alive if there is javascript code that has a reference to the DOM element. If there are no javascript references to the DOM element itself, then it will be garbage collected by the browser during the next garbage collection sweep.
A
reference in javascriptmeans a javascript variable, array, property, etc… that holds the DOM node. In your code above, I don’t see any such variables that are lasting so I don’t see any reason why the DOM node would not be garbage collected from this particular piece of code.Why do you think it’s being stored in browser memory?
To make sure a DOM element is cleared from memory, you do two things:
That’s it, there is nothing else.