How to add class to its parent div when clicked

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.

Read More

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

Related posts

1 comment

  1. 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");
      });
    
    });
    

Comments are closed.