Alexandro Giles
Alexandro Giles

Reputation: 492

Add a class to a child element only of the same div using jQuery

I want to add/remove a class to an element (child of the same div is being clicked) for example, if the user press the #first element: The first element should now have 2 classes: .block .active. and the

should now look red, But every other should remain intact. I've try the following (code below) nonetheless after I click on one block all of the blocks change their state and now all of them have both classes: .block .active.

Since I have a lot of blocks, If possible I don't want to use id selectors, just detect and apply the desired classes on the same parent div.

css

.block p{
 color: blue;
}
.block.active p{
 color: red;
}

html

<div class="block" id="first">
   <p> Element in blue </p>
</div>
<div class="block" id="second">
   <p> Element in blue </p>
</div>
<div class="block" id="third">
   <p> Element in blue </p>
</div>

jQuery

$(".block").click(function(){
    $("block").closest( "block" ).toggleClass( "active" );
});

Upvotes: 0

Views: 50

Answers (2)

Zam Abdul Vahid
Zam Abdul Vahid

Reputation: 2721

You were almost there. Instead of using .block & closest you can target the element being clicked with this.

In the below code, we are first removing the active class from all elements with class block and then applying the active class to the clicked element.

$(".block").click(function(){
    $('.block').removeClass('active');
    $(this).addClass( "active" );
});
.block p{
 color: blue;
}
.block.active p{
 color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="block" id="first">
   <p> Element in blue </p>
</div>
<div class="block" id="second">
   <p> Element in blue </p>
</div>
<div class="block" id="third">
   <p> Element in blue </p>
</div>

$(".block").click(function(){
    if ( $(this).hasClass('active')) {
      $(this).removeClass('active')
    } else {
      $('.block').removeClass('active');
      $(this).addClass('active');
    }
});
.block p{
 color: blue;
}
.block.active p{
 color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="block" id="first">
   <p> Element in blue </p>
</div>
<div class="block" id="second">
   <p> Element in blue </p>
</div>
<div class="block" id="third">
   <p> Element in blue </p>
</div>

Upvotes: 2

Aaron - Wolf X Machina
Aaron - Wolf X Machina

Reputation: 643

$(".block").click(function(){
    $(this).toggleClass("active");
});

Upvotes: 1

Related Questions