Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save danielhickman/5535ef8103da8a168a59 to your computer and use it in GitHub Desktop.
Save danielhickman/5535ef8103da8a168a59 to your computer and use it in GitHub Desktop.
JavaScript Remove and Remove Children
// Remove Element(s)
Element.prototype.remove = function() {
	this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
	for (var i = this.length - 1; i >= 0; i--) {
		if(this[i] && this[i].parentElement) {
			this[i].parentElement.removeChild(this[i]);
		}
	}
}
Element.prototype.removeChildren = function() {
	while (this.firstChild) {
		this.removeChild(this.firstChild);
	}
}
NodeList.prototype.removeChildren = HTMLCollection.prototype.removeChildren = function() {
	for (var i = this.length - 1; i >= 0; i--) {
		while (this[i].firstChild) {
			this[i].removeChild(this[i].firstChild);
		}
	}
}
@danielhickman
Copy link
Author

Partially from this StackOverflow answer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment