When removing an element with standard JavaScript, you must go to its parent first:
var element = document.getElementById("element-id");
element.parentNode.removeChild(element);
Having to go to the parent node first seems a bit odd to me, is there a reason JavaScript works like this?
From what I understand, removing a node directly does not work in Firefox, only Internet Explorer. So, to support Firefox, you have to go up to the parent to remove it's child.
Ref: http://chiragrdarji.wordpress.com/2007/03/16/removedelete-element-from-page-using-javascript-working-in-firefoxieopera/
For removing one element:
For removing all the elements with for example a certain class name:
The function name is
removeChild()
, and how is it possible to remove the child when there's no parent? :)On the other hand, you do not always have to call it as you have shown.
element.parentNode
is only a helper to get the parent node of the given node. If you already know the parent node, you can just use it like this:Ex:
https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild
=========================================================
To add something more:
Some answers have pointed out that instead of using
parentNode.removeChild(child);
, you can useelem.remove();
. But as I have noticed, there is a difference between the two functions, and it's not mentioned in those answers.If you use
removeChild()
, it will return a reference to the removed node.But if you use
elem.remove();
, it won't return you the reference.https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/remove
This behavior can be observed in Chrome and FF. I believe It's worth noticing :)
Hope my answer adds some value to the question and will be helpful!!
This is the best function to remove an element without script error:
Note to
EObj=document.getElementById(EId)
.This is ONE equal sign not
==
.if element
EId
exists then the function removes it, otherwise it returns false, noterror
.Functions that use ele.parentNode.removeChild(ele) won't work for elements you've created but not yet inserted into the HTML. Libraries like jQuery and Prototype wisely use a method like the following to evade that limitation.
I think JavaScript works like that because the DOM's original designers held parent/child and previous/next navigation as a higher priority than the DHTML modifications that are so popular today. Being able to read from one <input type='text'> and write to another by relative location in the DOM was useful in the mid 90s, a time when the dynamic generation of entire HTML forms or interactive GUI elements was barely a twinkle in some developer's eye.
IMHO: The reason for this is the same as I've seen in other environments: You are performing an action based on your "link" to something. You can't delete it while you're linked to it.
Like cutting a tree limb. Sit on the side closest to the tree while cutting or the result will be ... unfortunate (although funny).