Not at all, you can access the ul variable elsewhere. The example below shows that.
var ul = document.getElementById('someParent'); ul.remove(); console.log(ul); // ul and all li tags document.body.appendChild(ul); // ul appears again
An example is not a normal case. The usual case is that you want to access the DOM link in the event, for example, "click a button." This link will always be available until the event is untied. For instance:
var ul = document.getElementById('someParent'); var myButton = document.getElementById('myButton'); myButton.addEventListener('click', function () { ul.innerHTML += '<li>Some text</li>' }); ul.remove(); myButton.click();
To avoid memory leak in JS:
- make sure there are no DOM links using jQuery for Example.
- If you use DOM links in your application, set them to null or undefined when not in use.
So, you can change your event a bit, as shown below.
myButton.addEventListener('click', function () { // check ul belongs to visible DOM if (!document.body.contains(ul)) { ul = null; return; } ul.innerHTML += '<li>Some text</li>' });
source share