在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); }}
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"><br /><style type="text/css"> #ddd { width:400px; height:200px; background:red; } #eee { margin:20px; width:300px; height:100px; background:blue; } </style> 要去除的父元素</p> 子項目 </p><p> <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></p><p>
運行代碼
移除節點:
xxx.removeChild(obj) xxx是所刪除節點的父節點
xxx.removeNode(true) xxx是所要刪除的節點