skip to Main Content

just asking can you please tell me how can I achieve it when I clicked the button it should only add the class on its parent div. Currently its adding both the parent div even I click the first button

$( ".main-btn" ).each(function(index) {
    $(this).on("click", function(){
        $(".main").addClass("addClass")
    });
});
.main {
  background: yellow;
  margin-bottom: 3px;
  height: 50px;
  
}

.main.addClass {
  background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main">
  <div class="main-btn">Button</div>
</div>

<div class="main">
  <div class="main-btn">Button</div>
</div>

2

Answers


  1. There’s no need for .each() here, you can just reference the parent from the clicked element via .closest()

    $(".main-btn").on("click", function() {
      $(this).closest(".main").addClass("addClass");
    });
    .main {
      background: yellow;
      margin-bottom: 3px;
      height: 50px;
      
    }
    
    .main.addClass {
      background: green;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
    <div class="main">
      <div class="main-btn">Button</div>
    </div>
    
    <div class="main">
      <div class="main-btn">Button</div>
    </div>

    Also, you might not need jQuery

    document.querySelectorAll(".main .main-btn").forEach((btn) => {
      btn.addEventListener("click", (e) => {
        e.target.closest(".main").classList.add("addClass");
      });
    });
    
    Login or Signup to reply.
  2. You can use the parent() method:

    $(".main-btn").on("click", function() {
      $(this).parent().addClass("addClass");
    });
    .main {
      background: yellow;
      margin-bottom: 3px;
      height: 50px;
      
    }
    
    .main.addClass {
      background: green;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="main">
      <div class="main-btn">Button</div>
    </div>
    
    <div class="main">
      <div class="main-btn">Button</div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search