I have a following code in my html file and i want to access the grand parent of an element like the table which is the grand parent of td in the following code. For this I used the following jquery syntax but it displays “undefined”. can any one guide me where the problem is ?
<script type="text/javascript">
$(document).ready(function () {
alert($('td[id="4"]').parents().eq(1).attr("id"));
});
</script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div class="ui-layout-center" id="center" runat="server">
<table id="Table1" >
<tr id="tr1">
<td id="3" class="cell" >
first cell
</td>
<td id="4" class="cell">
second cell
</td>
</tr>
</table>
<br />
<br />
</div>
</form>
</body>
</html>
First off, you can’t run your code until the DOM is loaded. That means that you either must place it AFTER the relevant HTML in your source file or use jQuery’s method of waiting until the DOM is loaded:
Then, your code:
Is getting the first parent of the matching
tdelement. That first parent will be thetrtag which will alert it’s ID, not the<table>element’s id as you can see here: http://jsfiddle.net/jfriend00/rxUEp/If you want the table element’s ID, then it’s best to specify the actual parent you want with code like this:
Further fixing things up, ID values should start with an underscore or a letter, not a number and once you have a valid ID, you should use a much more efficient selector like this:
P.S. Another reason it’s good to use
.closest("table")to find the desired parent is that tables all have an implicit<tbody>tag (even if it’s not in your HTML) which means that the actual<table>tag is actually the 3rd parent up from your<td>. With.closest("table"), you don’t have to worry about these find details as jQuery just finds the one you have specified.