Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparing jQuery objects

I'm using a selector to get a group of objects (0 or more):

var $openMenus = $Triggers.filter(".trigger-hover");

Then I have an event attached to an item that may or may not be in the object above. Within that event where I want to compare the item that triggers the event to c

$([selector])
    .focus(function(){
        var $thisMenu = $(this);
        $openMenus.each(function(){
            if ($(this) != $thisMenu ){ 
                [do something]
            }
        }) 
    })

This will not work. While multiple jQuery objects may REFER to the same DOM object, they are actually separate jQuery objects and there for will never compare true.

Given that, what would be the way to handle this? How does one have two jQuery objects and compare them to see if one jQuery object refers to the same DOM element as another?

I could give each item I'm trying to select an ID, but am wondering if there is another way to go about it without having to add more to the HTML.

like image 207
DA. Avatar asked Feb 04 '10 15:02

DA.


People also ask

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 two objects in JavaScript?

We cannot just implement “==” or “===” operator to compare two objects. The better way to do the comparison is to use JSON. Stringify and compare the objects.

Is equal in jquery?

Approach 2: The == operator is used to compare two JavaScript elements. If both elements are equal then it returns True otherwise returns False.


1 Answers

Following on from bobince, instead of using wrapper[0] use the proper get(0) method to return the first element stored in your jQuery object.

var focused = null;  
$(':input').focus( function() {  
   focused = $(this);  
   compare($(this)); 
   //Compare them...trivial but will return true despite being different jQuery objects.
}).blur( function() {           
   focused = null; 
});

function compare(element) {
   if (element.get(0) === focused.get(0)) {
      alert('The same');
   }
}
like image 64
Craig Avatar answered Oct 12 '22 17:10

Craig