Wednesday, March 20, 2013

Native JavaScript | Remove DOM Element (easy!)

Hi, All.
If you'v been surfing my blog for a while, you may noticed that i am kindly a fun of simplifications and this article is not an exclusion from the rules. :)
Usually to remove an element, you need to perform quiet a few actions, as javascript gives you no easy way to do so.
I would like to explain and show how to easy remove DOM Element, don't forget to equip this function and add to your usable function list.
I also would really like if you still save the @author line, but i can forgive about it if you are really care for the code weight and minify the file.
A few actions to take before you remove is to find element, then traverse back to parent then from parent remove it's child. a complete mess - here it is simplified. Let's we move to the function itself and see how does it work.
/**
 * Remove DOM Element easier
 *
 * @author Valentin Ruskevych
 * @since 30 Dec 2012
 * 
 * @example
 *  document.getElementById('a').remove();
 */
HTMLElement.prototype.remove=function(){
 if (this.parentNode)
  this.parentNode.removeChild(this);
};

Let we break the function line by line to purely understand what is going on here.
Line: 1-9: Comments
Line: 10 : Add a new method "remove" to HTMLElement's prototype.
HTMLElement is a object that most page's elements inherits. If you know DOM Model, you probably know it.
Line: 11 : Ensure that the element we want to remove is having parent element by this.parentNode.
this - where comes from? this is belongs to context, and points to element that we called remove on.
example - document.getElementById('submit_button').remove(); - this points on element #submit_button
Line: 12 : finding parent of the element remove() called on, then remove it's child and pass "this" to the removeChild, so that making possible to remove parents child that is element we called remove on. a bit tricky, but, it is javascript :))

Hope i helped you to simplify/solve another problem :)

Sincerely,
VR

No comments: