How would you compare jQuery objects?

JqueryCompare

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

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])

Solution 2 - Jquery

Why not:

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

?

Solution 3 - Jquery

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 {}
});

Solution 4 - Jquery

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKyle HotchkissView Question on Stackoverflow
Solution 1 - JqueryChristian C. SalvadóView Answer on Stackoverflow
Solution 2 - JquerycletusView Answer on Stackoverflow
Solution 3 - JquerytbranyenView Answer on Stackoverflow
Solution 4 - JquerySalketerView Answer on Stackoverflow