Jquery - Check if spans has same content but independently for every div

Viewed 19

I want to check if the span has the same content as any other span. So I can add class to hide them. My goal is to keep the first one and hide the others.

Now here is the javascript that works but the result is not what I want.

var itemsFound = [];
$(".myspan").each(function(index) {
  if (itemsFound.indexOf($(this).text()) > -1) {
    $(this).addClass("hide");
  } else {
    itemsFound.push($(this).text());
  }
});
<div>
  <span class="myspan">Java </span>
  <span class="myspan">Php</span>
  <span class="myspan">Python </span>
  <span class="myspan">Php </span>
</div>

<div>
  <span class="myspan">Php </span>
  <span class="myspan">Java</span>
  <span class="myspan">Java </span>
  <span class="myspan">Python </span>
  <span class="myspan">Php </span>
</div>

The result is:

<div class="results">
Java
Php
Python
Php (hide)
Java (hide)
</div>

<div class="results">
Php (hide)
Java (hide)
Java (hide)
Python
Php (hide)
</div>

However, what I want is:

<div class="results">
Java
Php
Python
Php (hide)
Java (hide)
</div>

<div class="results">
Php 
Java 
Java (hide)
Python
Php (hide)
</div>

I also need a case insensitive solution.

1 Answers

You need a nested loop and reset the array each div

$("div").each(function() {
  let arr = [];
  $(".myspan", this).each(function() {
    var value = $(this).text().trim().toUpperCase();
    if (arr.includes(value)) $(this).hide();
    else arr.push(value);
  });
});
.show { color:red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div>
  <span class="myspan show">Java</span>
  <span class="myspan show">Php</span>
  <span class="myspan show">Python</span>
  <span class="myspan">php</span>
  <span class="myspan">Java</span>
</div>

<div>
  <span class="myspan show">Php</span>
  <span class="myspan show">Java</span>
  <span class="myspan">Java</span>
  <span class="myspan show">Python</span>
  <span class="myspan">Php</span>
</div>

Related