Reputation: 83
Given the following HTML structure:
<div class="wrap">
<div id="a"></div>
<div id="b"></div>
</div>
the following is false:
($('#a').parent() == $('#b').parent()); //=> false
even though:
$('#a').parent().children('#b').length; //=> 1
Could anyone explain why? Thanks!
Upvotes: 5
Views: 94
Reputation: 75317
Because of the same reason that $('#a) == $('#a')
is false
Each time jQuery builts a set of elements, it returns a new object (even if the jQuery object wraps the same elements as another). In JavaScript, the only time an object is equal to another, is if it's exactly the same object;
var a = {
foo: 1
};
var b = {
foo: 1
};
(a == b) // false;
To fix this, you can either compare the DOM objects directly (either by using .get(i)
or using the jQuery object like an array ([i]
)), or you get use the is()
method;
if ($('.foo').get(i) == $('.bar').get(i));
if ($('.foo')[0] == $('.bar')[0]);
if ($('.foo').is($('.bar')); // or even...
if ($('.foo').is('.bar'));
Upvotes: 3
Reputation: 337626
I'm not 100% on exactly why it doesn't work, but I believe it is because the elements are wrapped in jQuery objects which are inherently different per element.
As a workaround, you can compare the native DOM object, like this:
($('#a').parent()[0] == $('#b').parent()[0]); // true
Upvotes: 6