Вопрос

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 ?

Это было полезно?

Решение

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

Другие советы

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');

})
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top