Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for DOM equality with jQuery?

Tags:

jquery

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?

like image 574
Joseph Avatar asked Mar 15 '10 15:03

Joseph


People also ask

How to check equality in jQuery?

Approach 2: The == operator is used to compare two JavaScript elements. If both elements are equal then it returns True otherwise returns False.

How can you tell if two elements are the same?

If they have the same number of protons, they are the same element. If they have different atomic masses, then they are isotopes with different numbers of neutrons in the atoms. The number of electrons does not change the element - merely its ionisation state.

What is a jQuery object?

A jQuery object is created from the array elements in the order they appeared in the array; unlike most other multi-element jQuery operations, the elements are not sorted in DOM order. Elements will be copied from the array as-is and won't be unwrapped if they're already jQuery collections.


2 Answers

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")).... 
like image 64
user187291 Avatar answered Sep 25 '22 17:09

user187291


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()

like image 40
Matt Avatar answered Sep 21 '22 17:09

Matt