Reputation: 11125
Consider the following nested div
<div class="parent">
<div class="child"></div>
</div>
In jQuery, I do
$('.parent').click(function (e) {
e.target // this refers to .child instead of .parent
})
Is there a way to get the reference to .parent
in this case withut doing something like .closest()
?
Upvotes: 3
Views: 4575
Reputation: 11125
I was confused for a second why I couldn't simply use $(this)
reference. I am using Meteor
which binds this
to a different object in an event callback. In that case, you can just use event.currentTarget
, which I believe how jQuery binds this
reference anyway.
Upvotes: 3
Reputation: 87233
You can use $(this)
instead of e.target
and this
as you may want to use jQuery methods on it.
$('.parent').click(function(e) {
alert($(this).attr('class'));
});
.parent {
color: green;
}
.child {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div class="parent">
Parent
<div class="child">Clild</div>
</div>
$(this)
will always refer to the element on which the event has occurred.
Upvotes: 4