SNos SNos - 7 months ago 17
Javascript Question

Add class only to clicked element and it's children

I am trying to add a class to a

div
when another one is clicked.
Whit the code I have when I click on one
div
all of the get the class added.

FIDDLE

My jQuery is:

$(".front").click(function (event) {
// remove classes from all
$('.front .back').not($(this)).removeClass('back-Active');
// add class to the one we clicked
$('.front .back').addClass("back-Active");
event.stopPropagation();
});


How could I solve this?

Answer

Use $(this) in the event handler to refer to the element that is clicked.

$('.back', this)              // Select the element inside clicked element having `back` class
    .addBack(this)            // Add clicked element to the set
    .addClass("back-Active"); // Add class on the elements

Updated Fiddle

$(document).on('click', function() {
    $('.back').removeClass("back-Active");
});


$(".front").click(function(event) {
    // remove classes from all
    $('.back-Active').removeClass('back-Active');
    // add class to the one we clicked
    $('.back', this).addBack(this).addClass("back-Active");
    event.stopPropagation();
});
.back-Active {
    transform: scale(1.0) !important;
    opacity: 1 !important;
    transition: 400ms ease;
}

.front {
    background-color: red;
    width: 100px;
    height: 100px;
    margin: 20px;
}

.back {
    transform: scale(0.0);
    opacity: 0;
    background-color: green;
    width: 100px;
    height: 100px;
    margin-top: -18px;
    transition: 400ms ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="front">
    AAA
    <div class="back">AAA-BACK</div>
</div>

<div class="front">
    BBB
    <div class="back">BBB-BACK</div>
</div>

<div class="front">
    CCC
    <div class="back">CCC-BACK</div>
</div>

<div class="front">
    DDD
    <div class="back">DDD-BACK</div>
</div>

Comments