[js]removeChild注意事项

注意事项

<section id="section">
    <div id="test"></div>
</section>
<script>
    var div = test;
    section.removeChild(div);
    section.removeChild(div);
</script>

比如针对相同节点,两次进行removeChild操作。特别是含有引用关系的。div引用的节点虽然被移除,但是仍然存在于内存之中("The removed child node still exists in memory, but is no longer part of the DOM.")

removeChild在54.x版本chrome中的报错

If child is actually not a child of the element node, the method throws an exception. This will also happen if child was in fact a child of element at the time of the call, but was removed by an event handler invoked in the course of trying to remove the element (eg, blur.)

在MDN中有提到,The method throws an exception in 2 different ways:

解决方案

唯一可以辨识的就是移除了的节点它的parentNodenull.通过这个进行判断即可。

参考文献

  1. https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容