How can an object destroy an event in javascript?

I have this feature to create a div on the fly. But now I want to destroy this object in the onclick event, but I just don't know how to do it.

function creatediv(id) { var newdiv = document.createElement('div'); newdiv.setAttribute('id', id); newdiv.onclick=function(){this=null;}; //bad function document.body.appendChild(newdiv); } 

What am I missing?

thanks

+6
javascript dom object self-destruction
source share
3 answers

Just setting it to null will not destroy it. You need to remove it from the document tree, making sure that there are no links to it.

 function creatediv(id) { var newdiv = document.createElement('div'); newdiv.setAttribute('id', id); newdiv.onclick=function(e) { this.parentNode.removeChild(this); }; document.body.appendChild(newdiv); newdiv = null;//required in IE to prevent memory leak } 
+10
source share

The accepted answer seems to me wrong. Firstly, it does not take into account newdiv containing child elements, therefore, the proposed removal procedure prevents memory leak through locks (IE). Secondly, because of the position "newdiv = null", the created function immediately destroys the newly created element. I would recommend using the Douglas Crockfords cleanup function for the click handler, replacing d with this.

 function purge(d) { var a = d.attributes, i, l, n; if (a) { l = a.length; for (i = 0; i < l; i += 1) { n = a[i].name; if (typeof d[n] === 'function') { d[n] = null; } } } a = d.childNodes; if (a) { l = a.length; for (i = 0; i < l; i += 1) { purge(d.childNodes[i]); } } } 
+5
source share
 function removeElement(divNum) { var d = document.getElementById('myDiv'); var olddiv = document.getElementById(divNum); d.removeChild(olddiv); } 
0
source share

All Articles