Reputation: 80
I have the following structure:
<div class="section-header Generator" style="display: table-row;">Generator</div>
<div class="section-header Generator" style="display: table-row;">Generator</div>
<div class="section-header Generator" style="display: table-row;">Generator</div>
<div class="section-header Engine" style="display: table-row;">Engine</div>
<div class="section-header Engine" style="display: table-row;">Engine</div>
<div class="section-header Battery" style="display: table-row;">Battery</div>
Using JQuery, I want to remove the duplicates- so the above list would become:
<div class="section-header Generator" style="display: table-row;">Generator</div>
<div class="section-header Engine" style="display: table-row;">Engine</div>
<div class="section-header Battery" style="display: table-row;">Battery</div>
Any ideas how I'd acheive that? There's an old answer here but it doesn't appear to relate to my issue
Upvotes: 0
Views: 421
Reputation: 179
You could use eq() to target the second element with that class (it is zero based):
$('.Type your class here').eq(1).remove();
do that for every class
Upvotes: -1
Reputation: 638
Try this:-
$('.section-header').each(function(i, v){
var className = '.'+$(this).attr('class').split(' ').join('.');
$(className + ":not(:first)").remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="section-header Generator" style="display: table-row;">Generator</div>
<div class="section-header Generator" style="display: table-row;">Generator</div>
<div class="section-header Generator" style="display: table-row;">Generator</div>
<div class="section-header Engine" style="display: table-row;">Engine</div>
<div class="section-header Engine" style="display: table-row;">Engine</div>
<div class="section-header Battery" style="display: table-row;">Battery</div>
Upvotes: 2
Reputation: 80
Solution is here- I realised I was using the wrong search terms:
var seen = {};
$('.table-section-header').each(function() {
var txt = $(this).text();
if (seen[txt])
$(this).remove();
else
seen[txt] = true;
});
Upvotes: 2