I am having trouble using parent.removeChild(). I think I am using the correct syntax. Does anyone know what is wrong?
var parent = document.body
var child = document.getElementById("clueDiv")
parent.removeChild(child);
I am having trouble using parent.removeChild(). I think I am using the correct syntax. Does anyone know what is wrong?
var parent = document.body
var child = document.getElementById("clueDiv")
parent.removeChild(child);
If that does not work, probably child
is not child of document.body
.
Try with:
child.parentElement.removeChild(child)
Or, as @PaulS. said:
child.parentNode.removeChild(child)
You can also use ChildNode.remove()
:
var child = document.getElementById("clueDiv");
child.remove();
It's not supported in Internet Explorer, but you can use a polyfill:
if (!('remove' in Element.prototype)) {
Element.prototype.remove = function() {
if (this.parentNode) {
this.parentNode.removeChild(this);
}
};
}