删除节点操作(removeChild, removeNode)

来源:互联网 发布:电脑收发短信软件 编辑:程序博客网 时间:2024/05/21 09:39


目的: 删除 body 里面的所有 P 标签

方法:

       1. 通过 getElementsByTagName('p') 得到数组, 使用 while 循环一次删除

           注意: 不能使用 for()循环 for(var i=0; i<op.length; i++) {removeChild(op[i])}

                    这样删除只能删除p1, p3, 因为当执行一次 removeChild 之后, i会自动减少1,

                   所以应当使用 while 循环, 判断 length > 0 即可. 使用 removeNode(true);

 

        2. 通过 外层包裹一个标签, 删除包裹标签里面的所有元素达到目的.

           var len = document.getElementById('outer_Tag').children.length;

            for(var i=len-1; i>=0; i--){

                  document.getElementById('outer_Tag').removeChild(document.getElementById('outer_Tag').children(i));

            }

原创粉丝点击