Jonathan002 Jonathan002 - 1 year ago 79
jQuery Question

jQuery - Comparing .parent() to $('#id-name')

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

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download