移除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" οnclick="remove('ddd')">去除ddd元素</button><br /> <button type="button" οnclick="check('ddd')">检测ddd元素是否存在</button><br /> <button type="button" οnclick="remove('eee')">去除eee元素</button><br /> <button type="button" οnclick="check('eee')">检测eee元素是否存在</button> </body> </html>

移除节点:

xxx.removeChild(obj) xxx是所删除节点的父节点

xxx.removeNode(true) xxx是所要删除的节点

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值