26

I'm basically building a simple list, and one of the items in the list is selected. I'm accomplishing this by having a "selected" class applied to whichever item I want to have selected. I have two buttons that go forward and backward which traverse this list. However, when the user gets to the first or the last element in the list, I want to do a post back. This is where I'm stuck, because I'm having trouble identifying that the currently selected item is not the first or the last.

Simple Example:

<div id="list">
    <p>item 1</p>
    <p>item 2</p>
    <p class="selected">item 3</p>
</div>

Let's say the user presses the next button, at this point I'm checking for something similar to this:

if (jQuery('#list p.selected') == jQuery('#list p:last-child'))
    //do post back

However, this logic is returning false, which leads me to believe I'm approaching this the wrong way.

What is the best way for me to check for this kind of logic using jQuery?

Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
Joseph
  • 25,330
  • 8
  • 76
  • 125
  • Try doing a search for your question: http://stackoverflow.com/questions/2436966/how-would-you-compare-jquery-objects – PetersenDidIt Mar 15 '10 at 15:37
  • I did, and I'm not interested in comparing jQuery objects in particular. What I want is to check for DOM equality using jQuery. Perhaps that is one in the same, but I was assuming that jQuery objects get instantiated when you query for the DOM, and are treated separately. – Joseph Mar 15 '10 at 15:44
  • jQuery objects are just arrays of DOM objects and can preform more actions on them. – PetersenDidIt Mar 15 '10 at 15:47
  • I understand that but they themselves are not the DOM elements. They are more of an object wrapper around them, unless I'm misunderstanding the framework. – Joseph Mar 15 '10 at 15:52

2 Answers2

38

Although you can compare jquery objects as Matt has shown, or simply with index operator

if($("#list p.selected")[0] == $("#list p:last-child")[0])...

this is rarely needed with jQuery. There is a better way!

if($("#list p.selected").is(":last-child"))....

or the other way round, more readable

if($("#list p:last-child").is(".selected"))....
user187291
  • 53,363
  • 19
  • 95
  • 127
  • I actually did this but I think you're is basically the same thing: if ($('#list p:last-child').hasClass('selected'))... – Joseph Mar 15 '10 at 15:46
9

jQuery is an object, so you're technically comparing two different (but similar) objects, which will always be false.

Try:

if (jQuery('#list p.selected').get(0) == jQuery('#list p:last-child').get(0))

jQuery.get()

Matt
  • 74,352
  • 26
  • 153
  • 180