javascript – Script. Add remove class from the parent block when clicking on the child

Question:

The question is this: there are a number of parent blocks with the same class <div class-"block"></div> (main blocks), which contain child blocks:
( more button, close button).
It is necessary that, when you click on the button in more detail, the .active class is .active to the parent block (that is, to get <div class="block active"></div> )

the workpiece looks like this:

<div class="block">
<span class="readmore">подробнее</span>
<span class="close">закрыть</span>
</div>
<div class="block">
<span class="readmore">подробнее</span>
<span class="close">закрыть</span>
</div>
<div class="block">
<span class="readmore">подробнее</span>
<span class="close">закрыть</span>
</div>

what have tried:

$(".block .readmore").click(function() {
    $(".block").addClass("active"); //добавляем класс текущей (нажатой)
 })

$(".block .close").click(function() {
    $(".block").removeClass("active"); //добавляем класс текущей (нажатой)
 })

with this writing, it works (well, almost), only the class is assigned to all blocks, and I need the class to be assigned strictly to the parent element by clicking on the child.

Here's the script at work: https://jsfiddle.net/UeML6/295/

Answer:

Use $(this) and .parent () to get to the current block.

$(".block .readmore").click(function() {
    $(this).parents(".block").addClass("active"); //добавляем класс текущей (нажатой)
 })
$(".block .close").click(function() {
    $(this).parents(".block").removeClass("active"); //добавляем класс текущей (нажатой)
 })
.block{
    padding: 5px 15px;
    font-size: 18px;
    background: #FFCA00;
    margin: 5px;
    display: inline-block;
    
}
.block.active{
    background: #77EEC3;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="block">
    <span class="readmore">подробнее</span>
    <span class="close">закрыть</span>
</div>
<div class="block">
    <span class="readmore">подробнее</span>
    <span class="close">закрыть</span>
</div>
<div class="block">
    <span class="readmore">подробнее</span>
    <span class="close">закрыть</span>
</div>

PS Here I used .parents () , otherwise suddenly you decide to change the structure.

Scroll to Top