Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you compare jQuery objects?

Tags:

jquery

compare

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?

like image 833
Kyle Hotchkiss Avatar asked Mar 13 '10 01:03

Kyle Hotchkiss


People also ask

How do you compare objects with objects?

The equals() method of the Object class compare the equality of two objects. The two objects will be equal if they share the same memory address. Syntax: public boolean equals(Object obj)

What is the best way to compare objects in JavaScript?

Comparing objects is easy, use === or Object.is(). This function returns true if they have the same reference and false if they do not. Again, let me stress, it is comparing the references to the objects, not the keys and values of the objects. So, from Example 3, Object.is(obj1,obj2); would return false.

Can we compare objects in JavaScript?

In JavaScript, we cannot directly compare two objects by equality operators (double equals == or triple equals ===) to see whether they are equal or not. Comparing two objects like this results in false even if they have the same data.

How does Object comparison work in JavaScript?

Objects are not like arrays or strings. So simply comparing by using "===" or "==" is not possible. Here to compare we have to first stringify the object and then using equality operators it is possible to compare the objects.


3 Answers

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]) 
like image 103
Christian C. Salvadó Avatar answered Oct 16 '22 18:10

Christian C. Salvadó


Why not:

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

?

like image 33
cletus Avatar answered Oct 16 '22 17:10

cletus


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 {}
});
like image 23
tbranyen Avatar answered Oct 16 '22 18:10

tbranyen