Reputation: 10298
So I wanted to know why the .parent() of an element is returning false when compared to an $('#id') in jQuery.
I'm trying to compare them in an if statement on my code as follows:
if ($navbar.parent() === $('#sticky-wrapper'))
It returns false so I did some further testing on the console with just simple dom and came up with the output below:
> $('main')
< [<main class="main">…</main>]
> $('body')
< [<body>…</body>]
> $('main').parent()
< [<body>…</body>]
> $('main').parent() === $('body')
< false
> $('main').parent() == $('body')
< false
This is very confusing for me as the output appears the same in the console. Anyone have any idea on the real values that each method provides?
Any feedback would be greatly appreciated. : )
Upvotes: 0
Views: 918
Reputation: 171669
Use is()
. Clean to read, easy to write
if ($navbar.parent().is('#sticky-wrapper'))
Upvotes: 0
Reputation: 2543
You can't really compare jQuery objects like this, as each jQuery object is different. The DOM element a jQuery object references may be the same as another, but the root jQuery object will not. It's like two different cups that contain the same type of liquid (or something along these lines, perhaps two different maps that depict the same continent is a better example).
What you can do is compare the DOM elements, through jQuery, by getting the DOM element with get
(reference).
$('main').parent().get(0) === $('body').get(0) // true
..much like the following will also return true
:
$('body').parent().get(0) === $('html').get(0) // true
Upvotes: 6
Reputation: 2978
simply try this instead :
$('main').parent()[0] === $('body')[0]
or even this $('main').parent().is($('body'));
Upvotes: 1