what's the best way to remove the grapes duplicate from this? there are tons of ways of removing duplicates from simple arrays, but this would be an array with html elements
<div class="fruit">
grapes
</div>
<div class="fruit">
bananas
</div>
<div class="fruit">
grapes
</div>
I've tried using something like
$('.fruit').each(function () {
$('.fruit:has("' + $(this).text() + '"):gt(0)').remove();
});
what's the best way to remove the grapes duplicate from this? there are tons of ways of removing duplicates from simple arrays, but this would be an array with html elements
<div class="fruit">
grapes
</div>
<div class="fruit">
bananas
</div>
<div class="fruit">
grapes
</div>
I've tried using something like
$('.fruit').each(function () {
$('.fruit:has("' + $(this).text() + '"):gt(0)').remove();
});
Share
Improve this question
asked Aug 7, 2013 at 6:37
archytectarchytect
3,7255 gold badges25 silver badges31 bronze badges
6 Answers
Reset to default 3Try
var obj = {};
$('.fruit').each(function(){
var text = $.trim($(this).text());
if(obj[text]){
$(this).remove();
} else {
obj[text] = true;
}
})
Demo: Fiddle
:has
expects an element selector while :contains
takes a string
see http://api.jquery./contains-selector/
so this should do the trick:
$('.fruit').each(function () {
$('.fruit:contains("' + $(this).text() + '"):gt(0)').remove();
});
fiddle: http://jsfiddle/kam7E/
http://jsfiddle/S3wXM/1/
Assuming that you wish to remove only one of the duplicates.
Using contains, like the answer above but implementation is slightly different.
$($("div:contains('grapes')")[0]).remove();
http://api.jquery./jQuery.unique/ - This also might be of use to you.
var uniqueFruits = [];
$(".fruit").each(function(i,e){
var thisFruit = $.trim($(e).text());
if(uniqueFruits.indexOf(thisFruit) == -1)
uniqueFruits.push(thisFruit);
else
$(e).remove();
});
http://jsfiddle/a7E9e/
jsFiddle here: http://jsfiddle/THEtheChad/UKRwf/
var found = {};
var $unique_fruits = $('.fruit').filter(function(){
var data = this.innerHTML.trim();
if(!found.hasOwnProperty(data)) return found[data] = true;
});
Here is the working fiddle for this:-
http://jsfiddle/HwUUs/1/
$( "div:contains('grapes')" ).remove();
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744118868a4559304.html
评论列表(0条)