Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find parent div inside <td> with jQuery

Tags:

jquery

how can I find the parent id of the div inside the table? I have the following structure:

<div id="parent">
<table>
<tbody>
  <tr>                                             
   <td>                                     
     <div id="child" >      
 </div>
   </td>                    
 </tr>        
</tbody>
</table>
</div> 


<script type="text/javascript">  
$(document).ready(function() 
{               
   var parent = $("#child").parent().attr("id");
   alert(parent);
});   

When the div is inside < td> parent is empty. When I move the div outside < td> it works fine. Can you help me how to find the div inside ?

thanks

like image 304
zosim Avatar asked Jun 01 '11 09:06

zosim


1 Answers

You can use .closest(), it finds the closest parent which matches the specified selector. In your case:

 var parentId = $('#child').parent().closest('div').attr('id');

Documentation: http://api.jquery.com/closest/

like image 93
salgiza Avatar answered Sep 17 '22 15:09

salgiza