Reputation: 38805
If I write the listener as below,
$('.parent').bind('click', function() {
//...
})
<div class="parent">
<div class="children1"></div>
<div class="children2"></div>
<div class="children3"></div>
</div>
For example I clicked children2
, Is it possible to check which "children" DIV under parent
was clicked?
Thanks
Upvotes: 3
Views: 196
Reputation: 1074238
Yes, you can look at e.target
(change your handler to accept e
as an argument), possibly using closest
to get the first div
ancestor of the actual element clicked (in case those child div
s have descendants).
$('.parent').bind('click', function(e) {
// Here, `e.target` is the DOM element where the click occurred
var div = $(e.target).closest('div');
});
Alternately, if you only want the handler to fire when one of the children is clicked, you can use event delegation via delegate
or on
:
$('.parent').delegate('div', 'click', function(e) {
// Here, `this` is the child div that was clicked
});
// or
$('.parent').on('click', 'div', function(e) {
// Here, `this` is the child div that was clicked
});
Note that the order of args is different between delegate
(which I prefer for the clarity) and on
(which it seems like everyone else prefers).
Upvotes: 8
Reputation: 16922
You can look at the target of the event. Here the event is e.
$('.parent').bind('click', function(e) {
console.log(e.target);
});
Upvotes: 3
Reputation: 76
You should use
$('.parent').on('click', 'div', function() {
// ...
});
.on() should be used instead of .bind(). this
references the clicked div in the event-handler.
Upvotes: 0
Reputation: 10030
e.target.className
will get class name of div on which event fired.
$('.parent').bind('click', function(e) {
if(e.target.className.indexOf('children') != -1) { // <-- Perform function only if any child is clicked
// do something
}
})
Upvotes: 0