Question

I have the following code

<div id="parent">   
 <p>
 <a id="anchor"></a>
 </p>    
</div>

I have the following click event

 $("#anchor").click(function (e) {
 //need to find the first parent div id here 
} 

Any idea how to find the parent div of the anchor tag ?

Was it helpful?

Solution

$("#anchor").click(function (e) {
   var parentDiv = $(this).closest('div');
   //To get ID
   var divID=$(this).closest('div').attr('id');
 }); 

OTHER TIPS

I suggest you to replace id's if you have more then one instance of the mentioned html fragment in your document. Use classes instead.

$(document).on('click','.anchor', function(e){
    e.preventDefault();
    var $target = $(e.target),
        $parent = $target.closest('div.parent');

})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top