Reputation: 305
I have function that start working when I click on parent
and get parent id
( tmp
), but when I click on child
my function works too but return undefind
. How to get parent
id
doesn't matter on what I click child
or parent
or other elemnts in parent
div ?
<div class="parent" id="tmp">
<div class="child"></div>
</div>
.parent {
width: 100px;
height: 100px;
}
.child {
width: 50px;
height: 50px;
}
'click .parent': function(e){
console.log($(e.target).attr("id")); // from MeteorJS framework , but same sense
}
Upvotes: 1
Views: 2634
Reputation: 32354
try:
$('.parent').click(function(){
console.log($(this).attr('id'));
//console.log($(this)[0].id)
});
or
$('.parent').click(function(e){
console.log(e.currentTarget.id);
});
or
$('.parent').click(function(e){
console.log(e.delegateTarget.id);
});
Upvotes: 2
Reputation: 337560
In your click handler you should use this
to refer to the element that is handling the event:
'click .parent': function(){
console.log(this.id);
}
By using e.target
you're targeting the element which originated the event - which in the cases you describe would be the .child
element which has no id
attribute.
If you are unable to use the this
keyword due to restrictions imposed by Meteor, you could instead use the currentTarget
property on the event
, as it should have the same effect:
'click .parent': function(e){
console.log(e.currentTarget.id); // or $(e.currentTarget).prop('id')
}
Upvotes: 2
Reputation: 1364
Is this what you want?
$(function() {
$('div').click(function(e) {
var id = $(e.target).parent().attr('id');
if (typeof id === 'undefined') {
//return current element as this is a parent
console.log($(e.target).attr('id'));
} else {
//return parent's id
console.log(id);
}
});
});
.parent {
width:100px;
height:100px;
background: red;
}
.child {
width:50px;
height:50px;
background: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent" id="tmp">
<div class="child">
</div>
</div>
Upvotes: 1