在想要删除<body>中直接的一级父元素时,给body标签添加id名并进行如下操作:
<...>
<body id="body">
<div id="div1">
</div>
<script>
var test=document.getElementById("body");
var child=document.getElementByid("div1");
body.removeChild(child);
</script>
</body>
</...>
会发现操作无效。
这时候用parentNode可以实现目的:
<...>
<body id="body">
<div id="div1">
</div>
<script>
var test=document.getElementById("body");
var child=document.getElementByid("div1");
child.parentNode.removeChild(child);
</script>
</body>
</...>
使用parentNode可以获取 目标子元素 的 父元素 再对目标子元素执行removeChild()操作。
这里刨根问底,使用document.write()可以得到究竟父元素为哪个——哪个父元素被我们调用了:
<...>
<body id="body">
<div id="div1">
</div>
<script>
var test=document.getElementById("body");
var child=document.getElementByid("div1");
child.parentNode.removeChild(child);
document.write(child.parentNode);
</script>
</body>
</...>
得到结果为:
[object HTMLBodyElement]
查资料知:
HTMLBodyElement 接口提供了特殊属性(除了从常规 HTMLElement 接口继承的属性),用于操作 <body> 元素。