Home > other >  How to use each function jQuery to addClass on it's parent element
How to use each function jQuery to addClass on it's parent element

Time:10-20

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 >
  <div >Button</div>
</div>

<div >
  <div >Button</div>
</div>

CodePudding user response:

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 >
  <div >Button</div>
</div>

<div >
  <div >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");
  });
});

CodePudding user response:

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 >
  <div >Button</div>
</div>

<div >
  <div >Button</div>
</div>

  • Related