javascriptremovechild

Remove dom element without knowing its parent?


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!


Solution

  • Final update

    JS now has the .remove() method, available in all browsers since 2015. See caniuse.com/mdn-api_element_remove. Thanks to @rajniszp for pointing this out in the comments.

    Original

    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)