Lipak
Lipak

Reputation: 33

Target multiple elements using Jquery when condition matches

I have this html, Where "5" repeated twice.

<ul>
    <li>5</li>
    <li>6</li>
    <li>7</li>
    <li>5</li>
</ul>

So, I'm using click() on "LI" elements.

    var guess1 = "";
    var guess2 = "";
    var count = 0;

    $("li").click(function(){
        if ( count < 2 ){
             count++;
            if (count === 1 ) { 
                guess1 = $(this).text(); 
            } else{
                guess2 = $(this).text();
                    if (guess1 === guess2) {
                    $(this).css("background", "red"); // Here both matching "LI" should affect. Not only one "LI"
                }
            }      
        }
    });

Problem: I want that, when "guess1" === "guess2", then both matching "LI" (In this case LI containing value "5") should take bg color.

Please give any suggestion. Thanks :)

Upvotes: 0

Views: 59

Answers (2)

antonio Musella
antonio Musella

Reputation: 534

try using each function:

 var guess1 = "";
    var guess2 = "";
    var count = 0;

    $("li").click(function(){
        if ( count < 2 ){
             count++;
            if (count === 1 ) { 
                guess1 = $(this).text(); 
            } else{
           $('ul li').each(function(i)
                          {    
                          guess2 = $(this).text();
                          if (guess1 === guess2) {
                              $(this).css("background", "red");
                          }
                         });

            }      
        }
    });

this is a fiddle :

https://jsfiddle.net/nannizeta/mvw8zzcf/4/

Upvotes: 0

Barmar
Barmar

Reputation: 781068

Save the first element in a variable.

var guess1 = "";
var guess2 = "";
var count = 0;
var li1 = null;

$("li").click(function() {
  if (count < 2) {
    count++;
    if (count === 1) {
      guess1 = $(this).text();
      li1 = $(this);
    } else {
      guess2 = $(this).text();
      if (guess1 === guess2) {
        li1.css("background", "red");
        $(this).css("background", "red");
      }
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>5</li>
</ul>

Upvotes: 2

Related Questions