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