
正文
javascript --- 移除DOM节点
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
在IE中移除容器类节点,会引起内存泄露,最好是创建一个新的节点,比如div,然后将要删除的节点放入这个div中,再将div的innerHTML清空。其它的直接removeChild就可以了。
var removeNode = !+"\v1" ? function(){
var d;
return function(node){
if(node && node.tagName != 'BODY'){
d = d || document.createElement('DIV');
d.appendChild(node);
d.innerHTML = '';
}
}
}() : function(node){
if(node && node.parentNode && node.tagName != 'BODY'){
node.parentNode.removeChild(node);
}
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>移除节点</title>
<script type="text/javascript">
var removeNode = !+"\v1" ? function(){
var d;
return function(node){
if(node && node.tagName != 'BODY'){
d = d || document.createElement('DIV');
d.appendChild(node);
d.innerHTML = '';
}
}
}() : function(node){
if(node && node.parentNode && node.tagName != 'BODY'){
node.parentNode.removeChild(node);
}
}
var remove = function(id){
var ddd = document.getElementById(id);
removeNode(ddd);
}
var check = function(id){
var ddd = document.getElementById(id);
alert(ddd);
}
</script>
<style type="text/css">
#ddd {
width:400px;
height:200px;
background:red;
}
#eee {
margin:20px;
width:300px;
height:100px;
background:blue;
}
</style>
</head>
<body>
<div id="ddd">
要去除的父元素
<div id="eee">
子元素
</div>
</div>
<button type="button" onclick="remove('ddd')">去除ddd元素</button><br />
<button type="button" onclick="check('ddd')">检测ddd元素是否存在</button><br />
<button type="button" onclick="remove('eee')">去除eee元素</button><br />
<button type="button" onclick="check('eee')">检测eee元素是否存在</button>
</body>
</html>







