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
There’s no need for
.each()
here, you can just reference the parent from the clicked element via .closest()…Also, you might not need jQuery
You can use the
parent()
method: