删除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

posted @ 2020-12-04 11:29  China Soft  阅读(135)  评论(0编辑  收藏  举报