var a=$('#start > div:last-child');
var b=$('#start > div.live')[0];
alert(a==b)
alert(a==$(b))
It's always false. How can you compare two elements in jQuery?
thanks
This question is related to
javascript
jquery
dom
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
The collection results you get back from a jQuery collection do not support set-based comparison. You can use compare the individual members one by one though, there are no utilities for this that I know of in jQuery.
Random AirCoded example of testing "set equality" in jQuery:
$.fn.isEqual = function($otherSet) {
if (this === $otherSet) return true;
if (this.length != $otherSet.length) return false;
var ret = true;
this.each(function(idx) {
if (this !== $otherSet[idx]) {
ret = false; return false;
}
});
return ret;
};
var a=$('#start > div:last-child');
var b=$('#start > div.live')[0];
console.log($(b).isEqual(a));
For the record, jQuery has an is()
function for this:
a.is(b)
Note that a
is already a jQuery instance.
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
Source: Stackoverflow.com