Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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.

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading