开发者

find parent div inside <td> with 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


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/


If you mean you want to find the ID of the DIV that contains your table, then you can use closest()

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

Fiddle

EDIT

After reading the docs, closest() is better than parents() because it doesn't travel up to the root node. Thanks for the heads up Andy E


$(document).ready(function() 
{               
   var parent = $("#child").parent().attr("id");
   alert(parent);
});

You are trying to read the attribute of "id" of element and the has no attributes of name "id".

Following code will work:

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

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

This will give you alert message of "divParent".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜