如果未找到任何内容,则折叠HTML

时间:2013-06-10 18:25:55

标签: javascript jquery html

如果HTML元素不包含任何内容,我希望能够将其删除。

假设我们有一些标记,并且定位所有“collapse”类:

<div class='collapse'>[CONTENT?]</div>

如果有某些内容,则不要做任何事情。

但如果没有内容 - 没有字符串字符或空格 - 则完全删除div元素。

这在简单的情况下很容易实现,但是对于嵌套的内容,它会更加棘手。

这是一个演示,如果您尝试删除[CONTENTX?]字符串,然后看看HTML结构是什么,您会发现它不能完全正常工作。

如果div只有其他没有内容的div,那么应该将其视为没有字符或空格。

如果我们删除所有[CONTENTX?]字符串,那么我们应该看不到HTML结构。

有什么方法可以解决这个问题?

jsFiddle http://jsfiddle.net/97udq/

HTML:

<div id='container'>

    <div class='collapse'>
    [CONTENT1?]    
    </div>

    <div class='collapse'>
        [CONTENT2?]    
        <div class='collapse'>
            [CONTENT3?]    
            <div class='collapse'>[CONTENT4?]</div>
            <div class='collapse'>[CONTENT5?]</div>
        </div>
    </div>

</div>

使用Javascript:

$(function(){
    // function
    collapse();
    // Show HTML structure
    alert($('#container').html());
});

function collapse(){
    // Loop thru all collapse elements
    $('.collapse').each(function(){
        // Check for pure whitespace
        if($(this).html().replace(/\s+/g, '').length==0){
            // Nothing to see, so remove.
            $(this).remove();
        }
    });
}

CSS:

.collapse{
    height:20px;
    border:1px solid red;
}

3 个答案:

答案 0 :(得分:2)

我认为this能胜任这项工作;

它只使用text()代替html();

这是documentation

This one添加了trim(),但我觉得这不是你想要的。

function collapse(){
    $('.collapse').each(function(){
        if($(this).text().length==0){
            $(this).remove();
        }
    });
}

答案 1 :(得分:2)

这是完成你想要的另一种方式。它从底部向上递归DOM修剪节点。希望这会有所帮助。

    function prune(root) {
       $.each($(root).children(), function(){
          prune($(this));
       });
       if($(root).html().replace(/\s+/g, '').length==0 && $(root).hasClass("collapse")){
          $(root).detach();
       }
   }

Code integrated into your JSFiddle

答案 2 :(得分:1)

您需要重新创建.each()循环,但要反转。就像那样:

function collapse(){
    var el = $('.collapse');
    for(var i = el.length - 1; i >= 0; i--){
        if(el[i].innerHTML.replace(/\s+/g, '').length==0){
            $(el[i]).remove();
        }
    }
}

首先删除孩子,然后检查父母。

这里有一个小提琴:http://jsfiddle.net/97udq/5/


编辑:

我很想念你的问题,这是正确的解决方案:

function collapse(){
    $('.collapse').each(function(){
        var $this = $(this)
        var clone = $this.clone();
        clone.children().remove();
        if(clone.html().replace(/\s+/g, '').length==0){
            $this.children().appendTo($this.parent());
            $this.remove()
        }
    })
}

基本上,您克隆当前div,删除其子项,然后检查是否有一些文本。如果没有,你将他的孩子追加到他的父母那里

小提琴:http://jsfiddle.net/97udq/9/