Home > Software design >  Jquery - Check if spans has same content but independently for every div
Jquery - Check if spans has same content but independently for every div

Time:09-17

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 >Java </span>
  <span >Php</span>
  <span >Python </span>
  <span >Php </span>
</div>

<div>
  <span >Php </span>
  <span >Java</span>
  <span >Java </span>
  <span >Python </span>
  <span >Php </span>
</div>

The result is:

<div >
Java
Php
Python
Php (hide)
Java (hide)
</div>

<div >
Php (hide)
Java (hide)
Java (hide)
Python
Php (hide)
</div>

However, what I want is:

<div >
Java
Php
Python
Php (hide)
Java (hide)
</div>

<div >
Php 
Java 
Java (hide)
Python
Php (hide)
</div>

I also need a case insensitive solution.

CodePudding user response:

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 >Java</span>
  <span >Php</span>
  <span >Python</span>
  <span >php</span>
  <span >Java</span>
</div>

<div>
  <span >Php</span>
  <span >Java</span>
  <span >Java</span>
  <span >Python</span>
  <span >Php</span>
</div>

  • Related