测试两个元素是否相同

一开始我会怀疑这种方法是否奏效:

if ($('#element') == $('#element')) alert('hello');

但事实并非如此。如何测试元素是否相同?

66587 次浏览

I would use addClass() for marking the opened and you can check that easily.

Like silky or Santi said, a unique ID or class would be the easiest way to test. The reason your if statements don't work like you'd expect is because it's comparing 2 objects and seeing if they're the same object in memory.

Since it's always a new object getting created by $(this), they can never equal each other. That's why you have to test on a property of the object. You could get away with no unique id/class if each openActivity element was guaranteed to have different content that you could test against.

This should work:

if ($(this)[0] === $(this)[0]) alert('hello');

so should this

if (openActivity[0] == $(this)[0]) alert('hello');

As somebody already told, the same HTML element wrapped in two different moments generates two different jQuery instances, so they can never be equal.

Instead, the HTML elements wrapped may be compared that way, since the memory location they occupy is the same if it is the same HTML element, so:

var LIs = $('#myUL LI');
var $match = $('#myUL').find('LI:first');


alert(LIs.eq(0) === $match); // false
alert(LIs.get(0) === $match.get(0)) // TRUE! yeah :)

Best regards!

Or just

if (openActivity[0] == this) alert('hello');

(without a new jQuery instance ;-)

As of jquery 1.6 you can now simply do:

$element1.is($element2)

9 years later, without jQuery

If two elements are the same one, two elements must have the same pointer. Thus,

document.body === document.body // true
document.querySelector('div') === document.querySelector('div') // true
document.createElement('div') === document.createElement('div') // false