how to compare two elements in jquery
Every time you call the jQuery() function, a new object is created and returned. So even equality checks on the same selectors will fail.
<div id="a">test</div>
$('#a') == $('#a') // false
The resulting jQuery object contains an array of matching elements, which are basically native DOM objects like HTMLDivElement
that always refer to the same object, so you should check those for equality using the array index as Darin suggested.
$('#a')[0] == $('#a')[0] // true
For the record, jQuery has an is()
function for this:
a.is(b)
Note that a
is already a jQuery instance.
a.is(b)
and to check if they are not equal use
!a.is(b)
as for
$b = $('#a')
....
$('#a')[0] == $b[0] // not always true
maybe class added to the element or removed from it after the first assignment
You could compare DOM elements. Remember that jQuery selectors return arrays which will never be equal in the sense of reference equality.
Assuming:
<div id="a" class="a"></div>
this:
$('div.a')[0] == $('div#a')[0]
returns true.