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()
?
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()
?
- I don't think so!! See this fiddle. More understandable Fiddle – Guruprasad J Rao Commented Jul 22, 2015 at 6:44
-
1
I was so spoiled by jQuery's
this
that I forgot aboutevent.currentTarget
– Maximus S Commented Jul 22, 2015 at 7:04
3 Answers
Reset to default 4You 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./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.
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.
Just use this
, it refers to element on which event has occurred.
$('.parent').click(function (e) {
console.log(this);
})
DEMO