Question

How can I get nearby div's child element with jquery ? I'm trying to validate() my input element I need to get class=grand_child_02, when I'm in class=input_01

HTML:

<div class="parent">
    <div class="child_01">
      <h4 class="grand_child_01_01">
        <a href="#" class="link_01">link_01</a>
      </h4>
      <div class="grand_child_01_02">Some_text</div>
   </div>
   <div class="child_02">
     <div class="grand_child_02_01">
       <input type="text" class="input_01"/>
     </div>
   </div>
  </div>  

Thanks.

Was it helpful?

Solution 3

For clarification of my comments:

I have upvoted both the other answers as correct, but would suggest a slight tweak by only using siblings() without a filter.

var $target = $(this).closest('.child_02').siblings().find('.grand_child_02');

Where this is the input element you specified.

If you just use siblings(), it will work with additional added sibling div elements (which may be likely to occur in practical situations). I consider this a little more robust to changes (and insignificantly slower than with using the siblings filter).

e.g. in this example:

Fiddle: http://jsfiddle.net/TrueBlueAussie/tw3Yc/1/

OTHER TIPS

You can use closest(), siblings() and find():

var grand_child_02 = $(this).closest('.child_02').siblings('.child_01').find('.grand_child_02');

with $(this) refer to .input_01 element

use:

$(this).closest('.child_02').siblings('div').find('.grand_child_02')

Working Fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top