Javascript 从嵌套元素中删除重复文本

Javascript 从嵌套元素中删除重复文本,javascript,jquery,Javascript,Jquery,这是我的html: <div class="description">Example <div class="description">Foo <div class="description">Example <div class="description"> Example </div> </div> </div> </div>

这是我的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级。

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

// 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();
        }
    })
}); 

你试过什么?给我们看看你的代码,它成功了!非常感谢。如果没问题,也没什么好问的,你能给你的答案加个解释吗?你是个明星!再次感谢。