Test if two elements are the same

JavascriptJquery

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

As of jquery 1.6 you can now simply do:

$element1.is($element2)

Solution 2 - Javascript

This should work:

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

so should this

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

Solution 3 - Javascript

Or just

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

(without a new jQuery instance ;-)

Solution 4 - Javascript

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

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

Best regards!

Solution 5 - Javascript

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

Solution 6 - Javascript

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

Solution 7 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJonahView Question on Stackoverflow
Solution 1 - JavascriptchrisartonView Answer on Stackoverflow
Solution 2 - JavascriptepascarelloView Answer on Stackoverflow
Solution 3 - JavascriptFrancesco TerenzaniView Answer on Stackoverflow
Solution 4 - JavascriptyodabarView Answer on Stackoverflow
Solution 5 - JavascriptSantiView Answer on Stackoverflow
Solution 6 - JavascriptallenhwkimView Answer on Stackoverflow
Solution 7 - JavascriptPatView Answer on Stackoverflow