Maximus S
Maximus S

Reputation: 11125

Event.target refer to the child, not the parent

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

Answers (3)

Maximus S
Maximus S

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

Tushar
Tushar

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

Satpal
Satpal

Reputation: 133453

Just use this, it refers to element on which event has occurred.

$('.parent').click(function (e) {
    console.log(this);
})

DEMO

Upvotes: 2

Related Questions