Check if two elements are the same

I would suspect that this would work first:

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

But this is not so. How to check if items are the same?

+73
javascript jquery
Aug 13 '09 at 3:43
source share
6 answers

As in jquery 1.6, you can simply do:

 $element1.is($element2) 
+98
Oct 23 '13 at 15:58
source share

This should work:

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

so what is it

 if (openActivity[0] == $(this)[0]) alert('hello'); 
+73
Aug 13 '09 at 3:59
source share

Or simply

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

(without a new jQuery instance ;-)

+14
Mar 09 2018-11-11T00:
source share

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

Instead, wrapped HTML elements can be compared in this way, since their location in memory is the same if it is the same HTML element, therefore:

 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 :) 

Respectfully!

+12
Mar 08 2018-11-11T00:
source share

I would use addClass () to mark the open one, and you can easily verify this.

+5
Aug 13 '09 at 3:52
source share

Like Silky or Santi, a unique identifier or class would be the easiest way to test. The reason your if statements do not work as you expected is because it compares 2 objects and sees if they are the same object in memory.

Since a new object is always created using $ (this), they can never compare with each other. This is why you need to check the property of an object. You could leave without a unique id / class if each openActivity element did not have other content with which you could test.

0
Aug 13 '09 at 3:53
source share



All Articles