Frank Vel Frank Vel - 5 months ago 13
jQuery Question

affect divs of a class inside one container div using jquery .parent() and other relatives

I'm looking for a way to make the text inside divcontainer1 of class a bold, but I'm not entirely sure how to do this without affecting the div in container2, and affect both the inner and outer a. I'm sure this is possible with some parent().siblings().children().children-combination, but I'm not entirely sure how

Sample HTML

<divcontainer1>
<div>
<div class="a button">
button
</div>
</div>
<div>
<div>
<div class="a">
affect
</div>
</div>
</div>
<div>
<div class="a">
affect
</div>
</div>
<div>
<div class="b">
don't affect
</div>
</div>
</divcontainer1>
<divcontainer2>
<div class="a">
don't affect
</div>
</divcontainer2>


Sample JS

$(document).ready(function(){
$('.button').click(/* make all text inside container 1 bold*/)
});


I tried parent().parent().children().children().css('font-weight', 'bold'), but that didn't seem to work

Answer

Use .parents to find the divcontainer1 which contains the button. Then use .find to select the anchor elements within the container.

$('.button').click(function(){
    $(this).parents('divcontainer1').find('.a').css('font-weight', 'bold'); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<divcontainer1>
  <div>
    <div class="a button">
      button
    </div>
  </div>
  <div>
    <div>
      <div class="a">
        affect
      </div>
    </div>
  </div>
  <div>
    <div class="a">
      affect
    </div>
  </div>
  <div>
    <div class="b">
      don't affect
    </div>
  </div>
</divcontainer1>
<divcontainer2>
  <div class="a">
    don't affect
  </div>
</divcontainer2>

Note: It is not a good practice to use single letter class names. Also, it appears you may actually want to use the button and a elements instead of only divs.