I have divas A and B and their parent div C. There are a lot of C divs on the page. I need when I click on a certain div A to get the value of diva B enclosed in the same div C as div A.

    2 answers 2

    Fast decision.

    $('.a').on('click', function () { alert($(this).parents('.c').find('.b').html()); }); 
     .c { width: 300px; } .a { width: 100%; height: 100px; background-color: red; } .b { width: 100%; height: 100px; background-color: green; } 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="c"> <div class="a">1</div> <div class="b">2</div> </div> <div class="c"> <div class="a">3</div> <div class="b">4</div> </div> 

    • one
      1. When you subscribe, there is no verification that .a at all .c . 2. Such a subscription creates a bunch of handlers, although you can do with one. 3. parents instead of closest reduces efficiency. - Qwertiy
    • Yes, I agree with you. - Vitaliy Shevchenko

     $(function() { $("body").on('click', ".c .a", function() { $(this).closest(".c").find(".b").css("background", "red"); }); }); 
     div { margin: .5em; border: 1px solid; } div::after { content: attr(class); } 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class=c><div class=a></div><div class=b></div></div> <div class=c><div class=b></div><div class=a></div></div> <div class=c><div class=a></div><div><div class=b></div></div></div> <div class=c><div><div class=a></div></div><div><div class=b></div></div></div> <div class=c><div><div><div class=a></div></div><div><div class=b></div></div></div></div>