是否可以删除除 body 标签外没有父元素的 dom 元素?我知道使用像 jquery 这样的框架会很容易,但我试图坚持直接使用 javascript。
这是我发现的其他代码:
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;
}
}
谢谢!
最佳答案
你应该能够获取元素的父元素,然后从中移除元素
function removeElement(el) {
el.parentNode.removeChild(el);
}
更新
您可以将其设置为 HTMLElement 上的新方法:
HTMLElement.prototype.remove = function() { this.parentNode.removeChild(this); return this; }
然后执行 el.remove()
(这也会返回元素)
关于javascript - 在不知道其父元素的情况下删除 dom 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1804991/