Reputation: 779
I'm trying to obtain some insight in the context of a jQuery object. I've read a ton of questions on SO, but they all want to fix a specific problem, and the answers thus fix the problem, and didn't really provide me with the knowledge I'm hoping for.
So I have two buttons, and I have a click event that listens for both of them like so:
$('#copyRI, #copyIR').click(function () {...}
Now when I try to establish which element was clicked like so:
$('#copyRI, #copyIR').click(function () {
var test = $(this);
var test2 = $('#copyIR');
var compare = (test === test2);
}
compare
returns false when I click the button with id = #copyIR
when debugging I noticed that the context of test
and test2
are different:
Now I'm not looking for a way to successfully establish which button was clicked, but I want to obtain some insight in the concept of the "context" in a jQuery object.
Thanks in advance!
Upvotes: 3
Views: 411
Reputation: 49095
jQuery contexts (being an Object
) are compared by reference, so test === test2
would obviously return false
since each variable is pointing to a different jQuery context (the fact that both contexts internally contains a reference to same DOM object doesn't matter).
Try is()
instead:
var compare = $(this).is('#copyIR');
See Documetnation
Upvotes: 1
Reputation: 943564
When you call $(this)
you create a new jQuery object, instantiating it with an HTML Element.
When you call $('#copyIR')
you create a new jQuery object, instantiating it with a selector. This stores extra information in the object, including the selector itself.
Even if that wasn't the case, you would be creating two different objects and ===
(and ==
for that matter) test if two objects are the same object not if they are identical objects.
$(this) === $(this)
would also return false.
If you want to test if the elements are the same, then you can compare the underlying DOM nodes (since those will be the same object)
var compare = (test[0] === test2[0]);
Alternatively, you can just test if the object you have in the first place matches the selector:
var compare = test.is('#copyIR');
Upvotes: 2
Reputation: 160843
You could simply compare the id.
$('#copyRI, #copyIR').click(function () {
if (this.id === 'copyIR') {
// do something
}
}
Upvotes: 0
Reputation: 82241
You should rather use .is() method here.
Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.
CODE:
$('#copyRI, #copyIR').click(function () {
var test = $(this);
var compare = test.is('#copyIR')
}
Upvotes: 1