0

Possible Duplicate:
How would you compare jQuery objects?

I'm using jQuery to store the actively clicked item in a list of items. I want to detect if the newly clicked item is the same as the one previously clicked, to toggle the visibility of a supporting div. My code looks like this:

var curPin;

$('.pin').click(function(){
  var $pin = $(this);
  if (curPin == $pin){
    console.log('true');
  } else {
    curPin = $pin;
    console.log('false');
  }
}

Why is this not coming up as equal? Is there a better way to do this?

Community
  • 1
  • 1
mheavers
  • 29,530
  • 58
  • 194
  • 315
  • 4
    Because you are comparing jQuery objects, not DOM elements. jQuery objects are always different (like `{foo: 42} === {foo: 42}` are different), even if they contain the same DOM element(s). – Felix Kling Apr 23 '12 at 15:09
  • is there any other attribute of $pin like "unique ID" which can be compared for equality? – rt2800 Apr 23 '12 at 15:09
  • Would it not be worth comparing an attribute from the element, for instance the id? – Mark Walters Apr 23 '12 at 15:10

4 Answers4

3

Use if ($(this).is(curPin)) to check if the elements are the same.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
1

You're not comparing elements, but jQuery objects, and jQuery objects are always considered as different, even if they contain the exact same elements.

Comparing the DOM elements themselves indeed solves your problem. As suggested by Esailija, you can use the is() method to check is the jQuery object stored in curPin contains the current element:

var curPin;

$(".pin").click(function() {
    var $pin = $(this);
    if (curPin.is(this)) {
        console.log("true");
    } else {
        curPin = $pin;
        console.log("false");
    }
}
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • 2
    you could just use `if( curPin.is( this ) )` and it would have no side effects on OP's other code that could be using `curPin` as jQuery object – Esailija Apr 23 '12 at 15:14
  • @Esailija, very true, that avoids changing the type of `curPin`. Answer updated accordingly, thank you for this suggestion :) – Frédéric Hamidi Apr 23 '12 at 15:19
1

Just compare the DOM elements:

if(curPin.get(0) == $pin.get(0)) {
    // do something
}
Alp
  • 29,274
  • 27
  • 120
  • 198
0

If your element has an id, you can use that to compare against like so -

var curPin;  

$('.pin').click(function(){   
  var $pin = $(this).attr('id');  
  if (curPin == $pin)
  {     
    console.log('true');   
  } 
  else 
  {     
    curPin = $pin;     
    console.log('false');   
  } 
} 
Mark Walters
  • 12,060
  • 6
  • 33
  • 48