Tom Rudge Tom Rudge - 2 months ago 8
HTML Question

Add a class to the closest parent class only

I want to add a class via jQuery to a parent div element with a shared class. I can use .closest to add the class added to the correct div.class but it also adds the class to the rest of the divs with the same target class.

So I only want the class adding to the child button.



$('.trigger').on('click', function() {
$('.myclass').addClass('current');
});

.current {
margin: 30px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myclass">
<div style="background-color:red;">
<div style="padding:10px">
<button class="trigger">
Button
</button>
</div>
</div>
</div>

<div class="myclass">
<div style="background-color:blue;">
<div style="padding:10px">
<button class="trigger">
Button
</button>
</div>
</div>
</div>




Answer

You need to use .closest() to selecting parent element has .myclass.

$(".trigger").on("click", function() {
    $(this).closest(".myclass").addClass("current");
});
.current { margin: 30px }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myclass">
  <div style="background-color:red;">
    <div style="padding:10px">
      <button class="trigger">Button</button>
    </div>
  </div>
</div>
<div class="myclass">
  <div style="background-color:blue;">
    <div style="padding:10px">
      <button class="trigger">Button</button>
    </div>
  </div>
</div>