JavaScript之Dom操作【删除当前节点】

时间:2024-04-10 23:36:28
//最新更新:2017-11-25
//现在可以通过更强大而快捷的方式为所有的HTMLElement元素的Dom操作扩展新的方法【注意事项:处理HTMLElemnt元素时,此法对IE-8无效】
//原理:原型 (function(){
HTMLElement.prototype.remove = function(){
if(this.parentNode){
this.parentNode.removeChild(this);
}
}
})(); //demo
var div = document.createElement("div");
div.setAttribute("id","demo");
div.innerText = "hello";
document.body.append(div);
//div.remove();

传统方式:
document.getElementById("test").parentNode.removeChild(document.getElementById("test"));

function removeById(Id){
document.getElementById(Id).parentNode.removeChild(document.getElementById(Id))
}
function removeByClassName(classNames,indexs){

   for(var i = 0;i<classNames.length;i++){
document.getElementsByClassName(classNames[i])[indexs[i]].parentNode.removeChild(document.getElementsByClassName(classNames[i])[indexs[i]]
); } }

以清理百度文库为例:

step0:将文档全部页面都在网页上展开

step1:点击文库的全屏图标

step2:

clear();
function removeById(Id){
document.getElementById(Id).parentNode.removeChild(document.getElementById(Id))
}
function removeByClassName(classNames,indexs){
for(var i = 0;i<classNames.length;i++){
document.getElementsByClassName(classNames[i])[indexs[i]].parentNode.removeChild(document.getElementsByClassName(classNames[i])[indexs[i]]);
}
}
removeById("next_doc_box");
removeByClassName(["fix-searchbar-wrap","reader-tools-bar-wrap","pay-page-mod","ft","footer","new-ico-wkmember-free-doc"],[0,0,0,0,0,0]);