11

I have to compare two selectors and I was wondering why does this return false in firebug...and how do I compare two selectors

$('.product-info:last') == $('.product-info:last')

this is what I have to do

    var previous = $('.product-info:visible');
    if(previous == $('.product-info:last')){
        return false;
    }
Toon Krijthe
  • 52,876
  • 38
  • 145
  • 202
Matt Elhotiby
  • 43,028
  • 85
  • 218
  • 321
  • are you trying to compare the selector? the jquery object it returns? – Patricia Nov 14 '11 at 21:32
  • possible duplicate of [jQuery object equality](http://stackoverflow.com/questions/3176962/jquery-object-equality) – Blazemonger Nov 14 '11 at 21:34
  • comparing if its the same selector – Matt Elhotiby Nov 14 '11 at 21:34
  • Keep in mind that `$("#text")` is a jQuery object. `==` when comparing two objects only tests to see if they are the exact same object, not that they have the same contents. That's why your method of comparing doesn't work since each object in this `$('.product-info:last') == $('.product-info:last')` is different so they are never `==`. @Royi has a decent work-around. – jfriend00 Nov 14 '11 at 21:52

3 Answers3

14

The reason $('.product-info:last') !== $('.product-info:last') is because jQuery create a new object for each one of those, they are not the same jQuery object.

Use is instead to check if elements are the same.

previous.is('.product-info:last') 
aziz punjani
  • 25,586
  • 9
  • 47
  • 56
  • 1
    Caution: my read of [jquery is()](http://api.jquery.com/is/) is that it doesn't test if two selectors are **identical**, merely that they **overlap**. So for example this would work too: `previous.is(':last')` – Bob Stein Jul 28 '13 at 17:38
5

try :

$('.product-info:last').get(0) == $('.product-info:last').get(0)
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • I think ".get(0)" would be better, as that'd get you the DOM node and not a jQuery object. – Pointy Nov 14 '11 at 21:33
  • I always confusing between those two – Royi Namir Nov 14 '11 at 21:34
  • Works only if the selector contains exactly one DOM element. If the selector selects more than one element, this test will be incomplete. – Blazemonger Nov 14 '11 at 21:37
  • @mblase75 `If the selector selects more than one` **but it doesnt** ... first and last are returning 1. – Royi Namir Nov 14 '11 at 21:38
  • @RoyiNamir Yes, of course; I was obviously describing the problem with the *general* solution. Your approach only works with this specific selector, not with all possible selectors. – Blazemonger Nov 14 '11 at 21:39
2

Try the following:

var previous = $('.product-info:visible');
if (previous.is('.product-info:last')) {
    return false;
} 
Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114