views:

221

answers:

3

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!

A: 
document.body.removeChild(child);
Gregoire
@unknown: this answer only works for nodes that are immediate descendants of `document.body`. The other answers work for all cases, including descendants of `document.body`.
Crescent Fresh
As above, this answer only works on elements that are immediate descendants of body. Can someone moderate this?
adam
read the question: «a dom element that has no parent other than the body tag», so my response is perfectly valable
Gregoire
Apologies, I think the original question has been edited
adam
+4  A: 

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

function removeElement(el) {
el.parentNode.removeChild(el);
}
adam
+1  A: 

I think you can do something like...

              var child = document.getElementById(childDiv);
              //var parent = document.getElementById(parentDiv);
              child.parentNode.removeChild(child);

See node.parentNode for more info on that.

The Wicked Flea