从嵌套元素中删除重复的文本 [英] Remove text duplicate from nested element

查看:53
本文介绍了从嵌套元素中删除重复的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的html:

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

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

Now I want to remove all duplicate text i.e:

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

嵌套的准确/完全相同的元素可能会升至第8级.

Nesting could go up to 8th level with the exact/identical element.

推荐答案

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

you can try below code to fulfill your need :

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

这篇关于从嵌套元素中删除重复的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆