How to add class to its parent div when clicked

3.3k Views Asked by At

I am using this script in Wordpress hence the $=jQuery.

This currently adds .current class to all .col-xs-4.col-sm-4.feature_thumb divs.

How do I change this to only add the class to its parent's div?

jQuery(document).ready(function(){

jQuery(".feature_thumb a").click(function(){

    jQuery(".col-xs-4.col-sm-4.feature_thumb").addClass("current");

});

});

Can someone help me with this?

This is my html

<div class="col-xs-4 col-sm-4 feature_thumb">
    <a class="feature_thumb" id="feature_thumb1" onclick="return false;"  
    href="image1.jpg"><p>Image 1</p></a>
</div>

<div class="col-xs-4 col-sm-4 feature_thumb">
    <a class="feature_thumb" id="feature_thumb12" onclick="return false;" 
    href="image2.jpg"><p>Image 2</p></a>
</div>

Thank you

1

There are 1 best solutions below

2
On BEST ANSWER

You can use event.target to get a reference to what was clicked and then find the closest DOM node that matches your selector like so:

jQuery(document).ready(function() {

  jQuery(".feature_thumb a").click(function(event) {
    jQuery(event.target).closest(".col-xs-4.col-sm-4.feature_thumb").addClass("current");
  });

});

You likely need to remove the current classes from all the other nodes though so you probably want this:

jQuery(document).ready(function() {

  jQuery(".feature_thumb a").click(function(event) {
    jQuery(".col-xs-4.col-sm-4.feature_thumb.current").removeClass("current");
    jQuery(event.target).closest(".col-xs-4.col-sm-4.feature_thumb").addClass("current");
  });

});