javascript - 从嵌套元素中删除重复的文本

标签 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 层。

最佳答案

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

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

关于javascript - 从嵌套元素中删除重复的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28497971/

相关文章:

javascript - 如何使用 Modernizr.js 测试 DOM4 Mutation Observers?

javascript - 计算最大值并将背景设置为相等的父级

javascript - 主干从模型与集合中获取数据

javascript - toLocaleString() 在不同浏览器中的不一致行为

javascript - 未捕获的语法错误 : Unexpected token }

javascript - 淡出后的进度

javascript - 了解代码片段中的条件运算符和条件赋值

javascript - 在输出之前随机化 JSON 内容的内容

javascript - 单击“喜欢”按钮时,它应该显示特定数据吗?

jquery - 在 AJAX 和 WordPress 中找不到数据时显示消息