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.
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.
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.
Approach 2: The == operator is used to compare two JavaScript elements. If both elements are equal then it returns True otherwise returns False.
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');
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With