108

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?

cletus
  • 616,129
  • 168
  • 910
  • 942
Kyle Hotchkiss
  • 10,754
  • 20
  • 56
  • 82
  • 3
    `var $parent = $(this).parent(), $body = $('body');` `var theSame = $parent.is($body);` http://api.jquery.com/is/#is-jQuery-object – Victor Oct 30 '13 at 13:55
  • 1
    $(this).parent().is($('body')); //or check for anything else besides $('body') http://stackoverflow.com/a/6986013/112100 – Omu Jul 26 '14 at 07:24

4 Answers4

161

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])
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • 1
    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 Mar 13 '10 at 02:06
  • 1
    @Jimmy, yes but this is enough for the OP requirements, he wants only to know "... if the parent element is the body ..." – Christian C. Salvadó Mar 13 '10 at 02:11
  • 2
    Can shorten to: if(this.parentNode === document.body); – ehynds Sep 29 '11 at 16:14
  • IMHO, this might be useful [http://learn.jquery.com/using-jquery-core/jquery-object/#not-all-jquery-objects-are-created](http://learn.jquery.com/using-jquery-core/jquery-object/#not-all-jquery-objects-are-created) – Ajeeb.K.P Aug 21 '15 at 08:37
61

Why not:

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

?

cletus
  • 616,129
  • 168
  • 910
  • 942
21

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");

  // They are equal
  if (divs.length == divs2.length && divs.length == divs.filter(divs2).length) {         

  // They are not
  } else {}
});
tbranyen
  • 8,507
  • 1
  • 21
  • 18
1

I stumbled on these answers and wondered which one was better. It all depends on your needs but the easiest to type, read and execute is the best of course. Here's the perf testcase I made to make a decision.

http://jsperf.com/jquery-objects-comparison

Salketer
  • 14,263
  • 2
  • 30
  • 58