Remove dom element without knowing its parent?

Matrym picture Matrym · Nov 26, 2009 · Viewed 37.9k times · Source

Is it possible to remove a dom element that has no parent other than the body tag? I know this would be easy with a framework like jquery, but I'm trying to stick to straight javascript.

Here's the code I've found to do it otherwise:

function removeElement(parentDiv, childDiv){
     if (childDiv == parentDiv) {
          alert("The parent div cannot be removed.");
     }
     else if (document.getElementById(childDiv)) {     
          var child = document.getElementById(childDiv);
          var parent = document.getElementById(parentDiv);
          parent.removeChild(child);
     }
     else {
          alert("Child div has already been removed or does not exist.");
          return false;
     }
}   

Thanks!

Answer

Adam Hopkinson picture Adam Hopkinson · Nov 26, 2009

You should be able to get the parent of the element, then remove the element from that

function removeElement(el) {
el.parentNode.removeChild(el);
}

Update

You can set this as a new method on the HTMLElement:

HTMLElement.prototype.remove = function() { this.parentNode.removeChild(this); return this; }

And then do el.remove() (which will also return the element)