The Unforgiving DOM, How to Remove an Object from the DOM

Sep 30, 2006 by

This morning when working on some user interface pieces, I came upon a situation that required me to remove an HTML element (in this case a tag) from the page.  Not just hide it, but delete it completely.  This, of course, is done through the Document Object Model.The cross-browser way to accomplish this is as such, where the span element has an ID of ‘MySpan’:

myObj = document.getElementById('MySpan');
myObj.parentNode.removeChild(myObj);

That’s finding the span in the DOM and then telling its parent node to delete the span as a child node.  (You could do this with myObj.removeNode() without needing the parent, but that does not work in all browsers).

However, my situation was a tiny bit different… I needed the span element to be removed if it (itself) were clicked on.  Again, we go to the DOM, and we modify the span element’s onclick behavior:

myObj = document.getElementById('MySpan');
myObj.onclick = function removeMe() { this.parentNode.removeChild(this); }

It’s that simple. 

So why is this post called ‘The Unforgiving DOM’?  Well, think about it, that onclick handler is telling the span element to tell it’s own parent to execute the removal.  Now, if the removeNode() method mentioned above worked in all browsers, we’d have simple DOM object suicide (myObj.removeNode())…. but instead, we have to tell the object to tell its parent to commit filicide.  Seems a little harsh, eh?  Almost Shakespearean.

 

read more

Related Posts

Tags

Share This