Ensure two items are siblings in JS / jQuery
Asked Answered
H

2

5

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!

Honaker answered 20/2, 2012 at 14:53 Comment(0)
S
6

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

Schurman answered 20/2, 2012 at 14:57 Comment(0)
S
3

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')); 
Seline answered 20/2, 2012 at 15:1 Comment(1)
$('.foo').is('.bar') should suffice.Moss

© 2022 - 2024 — McMap. All rights reserved.