Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to compare two elements in jquery [duplicate]

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

like image 212
zjm1126 Avatar asked Mar 09 '10 09:03

zjm1126


5 Answers

For the record, jQuery has an is() function for this:

a.is(b)

Note that a is already a jQuery instance.

like image 108
e-motiv Avatar answered Oct 06 '22 14:10

e-motiv


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.

like image 40
Darin Dimitrov Avatar answered Oct 06 '22 14:10

Darin Dimitrov


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
like image 38
Anurag Avatar answered Oct 06 '22 14:10

Anurag


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

like image 33
Jondi Avatar answered Oct 06 '22 12:10

Jondi


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));
like image 40
gnarf Avatar answered Oct 06 '22 12:10

gnarf