29er 29er - 4 months ago 10
Javascript Question

JQuery - getting the parent div from a nested element ID

i am trying to access an element by using an ID of one of it's nested elements, using JQuery. For example : I need to find 'myDiv' from its nested 'searchBox' element. The issue is that the hierarchy changes and the searchBox will not always be in the same nested position. so i essentially need something that says: Give me the DIV that contains the element with the ID of 'searchBox'.(see below) Any suggestions?
Thanks!

<div id="myDiv" class="CommonGridView_ListBoxPopupPanel">
Some text here :
<table><tbody><tr><td><input class="tboxw" type="text" id="btnFind"/></td>
<td>some content</td> </tr>
<tr> <td><textarea id="searchBox">text area content</textarea> </td>
</tr>
</tbody>
</table>
<table><tr><td></td></tr></table>
</div>

Answer

If you want to find the wrapping DIV element (regardless of the ID on that DIV) then you'll want this jQuery selector:

$("#searchBox").closest("div");

The closest([selector]) function will find the wrapping element that matches the selector.

Comments