Reputation: 2181
If you have a click function for a link in a div, and want to know the id of a div that the click div is a child of (maybe 3rd child, maybe 5th child), is this the way to get it (it's working, but I'm wondering if there's a better way if you know the class of the parent?)
<div class="cont" id="c_22">
<div>
<div>
<div class="del"><a href="#">DELETE</a></div>
</div>
</div>
</div>
This within click function...
alert($(this).closest('.cont').attr('id'))
Sometimes the "del" div has more divs surrounding it, so I can't rely on going up a certain number of divs. The inner divs have other stuff in them, but I've left it out to keep things easy.
Thanks for your help.
Upvotes: 0
Views: 50
Reputation: 2952
I think that It will help you
$(".cont a").on('click', function(){
console.log($("a").parent().closest('.cont').attr('id'))
});
Upvotes: 1
Reputation: 82241
You have already used one of the best way of doing it. You can also use .parents()
:
$(this).parents('.cont').attr('id')
Upvotes: 2