Reputation: 633
Basically what I'm trying to do is identify if there is any duplicate content from a list of items that all share the same class, and then remove any duplicates.
Here's my attempt so far but has been unsuccessful:
var listItemContent = $(".featured-listing").textContent;
if (listItemContent === listItemContent) {
$('.featured-listing').hide();
}
This isn't really working, and I'm not surprised as js is not my strong suit and even reading it it looks like it would take the content of an instance of ".featured-listing", compare it to itself and then hide it, resulting in all instances of that class being hidden. The problem is I'm not really sure how to:
Upvotes: 0
Views: 362
Reputation: 2902
You can filter your jQuery
list object taking those that are repeated and hide them. Check the next fiddle
, the technique is to check those items that have a previous sibling with the same text content and create a new jQuery
list with them:
let items = $(".featured-listing li");
let repes = items.filter((ind, itm) => $(itm).prevAll(`:contains(${itm.innerText})`).length);
repes.remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="featured-listing">
<li>1 - Content 01</li>
<li>2 - Content 02</li>
<li>1 - Content 01</li>
<li>3 - Content 03</li>
<li>4 - Content 04</li>
<li>2 - Content 02</li>
<li>5 - Content 05</li>
<li>6 - Content 06</li>
<li>2 - Content 02</li>
<li>7 - Content 07</li>
</ul>
Upvotes: 1
Reputation: 9988
Get all the featured-listings
. Define a main object
which holds all the texts and then delete an element if there is the same text:
var elements = {};
$('.featured-listsing').each(function () {
var currentText = $(this).text();
if ( elements[currentText] )
$(this).remove();
else
elements[currentText] = true;
});
Upvotes: 1
Reputation: 21465
Try this snippet:
var listItemContents = [];
$(".featured-listing li").each(function() {
var text = $(this).text();
if (listItemContents.indexOf(text) == -1) {
listItemContents.push(text);
}
else {
$(this).remove();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="featured-listing">
<li>Text 1</li>
<li>Text 2</li>
<li>Text 3</li>
<li>Text 1</li>
<li>Text 4</li>
<li>Text 2</li>
</ul>
It just loop through all items checking their content by an array. If the text isn't found in the array, it adds the item. If it is found, it removes the list item.
I'm not sure if that html is like yours since you didn't added it in your post. If you do, we can have a clearer idea of what would works better for you.
Upvotes: 2