Question

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!

Was it helpful?

Solution

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

Example fiddle

OTHER TIPS

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')); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top