其他分享
首页 > 其他分享> > 删除dom空元素方法:

删除dom空元素方法:

作者:互联网

 

Js:

<html>
<head>
</head>
<body>
<div id="test"><span><imgs/></span></div>
</body>
</html>


<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>

<script>

    var dom = document.getElementById("test");


    var widthTraversal = function(obj,result){
        var stack = [];
        stack.push(obj);
        while(stack.length){
            var item = stack.shift();
            result.push(item);
            var childs = item.children;
            if(childs){
                for(var i = 0; i < childs.length; i++){
                    stack.push(childs[i]);
                }
            }
        }
    }
    var result1 = [];
    widthTraversal(dom, result1);

    for (var x = result1.length - 1; x >= 0; x--) {
        var item = result1[x];
        if (item.children.length == 0 && item.innerHTML == "" && item.tagName != "IMG") {
            item.parentNode.removeChild(item);
        }
    }

    console.log(result1);
    console.log($("#test").html());

</script>

  

 

 

Jquery:

<html>
<head>
</head>
<body>
<div id="test">
    <span>
        <div>

        </div>
        </span>111

</div>
</body>
</html>


<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>

<script>

    var str = $("#test").html();
    var dom = $("<div>" + str + "</div>")[0];

    var widthTraversal = function (obj, result) {
        var stack = [];
        stack.push(obj);
        while (stack.length) {
            var item = stack.shift();
            result.push(item);
            var childs = item.children;
            if (childs) {
                for (var i = 0; i < childs.length; i++) {
                    stack.push(childs[i]);
                }
            }
        }
    }
    var result1 = [];
    widthTraversal(dom, result1);

    for (var x = result1.length - 1; x >= 0; x--) {

        var item = result1[x];
        var noRemoveTags = ["IMG", "INPUT", "TABLE", "VIDEO"];
        if (item.children.length == 0 && item.innerHTML == "" && noRemoveTags.indexOf(item.tagName) == -1) {
            item.parentNode.removeChild(item);
        }
    }

    console.log(result1);
    console.log($(dom).html());

</script>

  其他:

 

https://segmentfault.com/q/1010000007407908?_ea=1336748

let reg = /<([a-z]+?)(?:\s+?[^>]*?)?>\s*?<\/(?!img)\1>/ig

标签:childs,删除,dom,元素,result1,item,length,var,stack
来源: https://www.cnblogs.com/chinasoft/p/14084906.html