从嵌套元素中删除文本副本

时间:2015-02-13 10:54:44

标签: javascript jquery

这是我的HTML:

<div class="description">Example
    <div class="description">Foo
        <div class="description">Example 
            <div class="description"> Example </div>
        </div>
    </div>
</div>

现在我要删除所有重复的文本,例如:

   <div class="description">Example
      <div class="description">Foo</div>
   </div>

使用完全/相同的元素,嵌套可以达到第8级。

1 个答案:

答案 0 :(得分:1)

您可以尝试以下代码来满足您的需求:

// first of all, looping of all target elements
$('.description').each(function(){
    var text = $(this).clone().children().remove().end().text().trim(); // this will first make clone of target, then remove all children of target and then get remaining text "without including unnecessary children text" and then trim "for remove unnecessary white space"
    $(this).find('.description').each(function(){ // Then looping of internal elements to check their text
        var subtext = $(this).clone().children().remove().end().text().trim(); // internal element's text "without including sub elements unnecessary text"
        if(subtext === text){ // compare target text and internal element's text : if both are identical, then we allow to remove internal element
            $(this).remove();
        }
    })
}); 
相关问题