how to compare two elements in jquery
JavascriptJqueryDomJavascript Problem Overview
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
Javascript Solutions
Solution 1 - Javascript
For the record, jQuery has an is()
function for this:
a.is(b)
Note that a
is already a jQuery instance.
Solution 2 - Javascript
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.
Solution 3 - Javascript
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
Solution 4 - Javascript
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
Solution 5 - Javascript
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));
Solution 6 - Javascript
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.