Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 399
Matrym Avatar asked Nov 26 '09 18:11

Matrym


People also ask

How do you remove the parent element without removing a child?

To remove the parent element without removing its children, call the replaceWith() method on the parent element passing it the child nodes as a parameter, e.g. parent. replaceWith(... parent. childNodes) .

How do you remove child DOM element?

Child nodes can be removed from a parent with removeChild(), and a node itself can be removed with remove(). Another method to remove all child of a node is to set it's innerHTML=”” property, it is an empty string which produces the same output.


1 Answers

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)

like image 63
Adam Hopkinson Avatar answered Oct 05 '22 06:10

Adam Hopkinson