I am trying to access an element using the identifier of one of its nested elements using jQuery. For example: I need to find "myDiv" from its nested element "searchBox". The problem is that the hierarchy is changing and the searchBox is not always in the same nested position. so I need something that says: Give me a DIV that contains the element with the id "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>
If you want to find a wrapping DIV element (regardless of the identifier on that DIV), you will need this jQuery selector:
$("#searchBox").closest("div");
c losest ([selector]) wrapper, .
$('#searchBox').parents('#myDiv')
, .
var $parentDiv = $('#searchBox');
.parents, , , , getElementById. , , className, .closest('div.class'), , .
.closest('div.class')
, .closest, - , searchBox .
if ( $element.closest('#searchBox').length ){ //do something }
$('#searchBox').parents('div:first')
$('#searchBox').parents('div:eq(0)')
:
var searchBox = $('#searchBox'); // Have the searchBox jQuery object, so find the ancestors that match a specific selector. var parentDiv = searchBox.parents('div#myDiv');
Full documentation is available here .
A complex nested example:
find the text value a-N1 by clicking on -N2? !!
Decision:
<ul class="ul-N1"> <li class="li-N1"> <a class="a-N1"></a> <ul class="ul-N2"> <li class="li-N2"> <a class="a-N2"> </a> </li> </ul> </li> </ul>
Jquery:
var a-N1 = $ (this) .closest (". ul-N1.li-N1"). find (". a-N1"). text ();