tags:

views:

827

answers:

3

So I'm trying to figure out how to compare two jQuery objects, to see if the parent element is the body of a page.

here's what I have:

if ( $(this).parent() === $('body') ) ...

I know this is wrong, but if anybody understands what I'm getting at, could they point me towards the correct way of doing this?

+6  A: 

You need to compare the raw DOM elements, e.g.:

if ($(this).parent().get(0) === $('body').get(0))

or

if ($(this).parent()[0] === $('body')[0])
CMS
That will only ensure equality if the jQuery object matched a single DOM element. If there were multiple matches you'd need a loop of some sort to compare each one.
Jimmy Cuadra
@Jimmy, yes but this is enough for the OP requirements, he wants only to know "... if the parent element is the body ..."
CMS
+2  A: 

Why not:

if ($(this).parent().is("body")) {
  ...
}

?

cletus
+1  A: 

Looping is not required, testing the single first node is not required. Pretty much nothing is required other than ensuring they are the same length and share identical nodes. Here is a small code snippet. You may even want to convert this into a jquery plugin for your own uses.

jQuery(function($) {
    // Two separate jQuery references
    var divs = $("div");
    var divs2 = $("div");

    // Test equality
    if( divs.length === divs2.length && divs.length === divs.filter(divs2).length ) {
        // They are equal
    }
    else {
        // They are not
    }
});
lark