The jQuery function ($
) returns a new Object
(commonly referred to as a "jQuery object"), which represents a collection of DOM elements (as well as some properties and methods to manipulate the collection). Even if the same elements are selected (same or different selectors, even), meaning the jQuery objects contain the same DOM elment(s), they still wouldn't be equal. JS objects are never ==
(or ===
) unless they actually refer to the same object.
For example, $("#element_id") === $("#element_id")
is false
even though they are selecting the same element.
But var el = $("#element_id"), ref = el; alert(el === ref);
would alert true
because they both refer to the same object.
If you want to compare these elements, compare references to DOM elements, like this:
$('#first').on('click', function(){
var element = this;
$('.myLink').each(function(i, el){
if (this === element) {
alert(i + ' equals');
}
});
});
DEMO: http://jsfiddle.net/HEmB7/
Something to read about object equality in JavaScript: Object comparison in JavaScript - it is a duplicate, but it, and the duplicated post, contain great information.
Another approach for this comparison is with the jQuery .is()
method. If used appropriately, it can be very powerful. It accepts a string selector, function, jQuery object, or DOM element reference. In a simple example like yours, it could easily be used (but I almost find it too much, because a jQuery object needs to be created and extra processing is done by .is()
) when you can just use ===
which is valid and reliable too...although .is()
is slightly more readable. Here's how it could be used:
$('#first').on('click', function(){
var element = $(this);
$('.myLink').each(function(i, el){
if (element.is(this)) {
alert(i + ' equals');
}
});
});
DEMO: http://jsfiddle.net/HEmB7/2/
Reference: