Test if two elements are the same

Viewed 66191

I would suspect this to work at first:

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

But it does not. How does one test if elements are the same?

7 Answers

This should work:

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

so should this

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

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

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

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.

Related