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!
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) .
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With