【发布时间】:2017-08-14 19:18:59
【问题描述】:
是否可以删除除了 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;
}
}
谢谢!
【问题讨论】:
-
仅供参考
body是一个完全有效的父母。 -
每个元素都有一个父元素
-
@connorspiracist 除了
document -
@adam
document不是元素,它是一个节点(文档节点),因此不属于元素 -
未添加到树中的文档片段没有父级。