Search code examples
javascriptjquery

How to toggle class of closest element


I am using the below code to click on an image within the .process class and when clicked the .process-info with toggle class of .process--shown.

This code works; however, it will toggle the class of process--shown for all elements on the page with the class of .process-info;

I only want the element clicked on to acitivate

$(document).ready(function(){

  $(".process .process--img").click(function(){
  $(".process .process--info").toggleClass("process--shown") 
});    
  $(".process .process--info").click(function(){
    $(".process .process--info").toggleClass("process--shown") 
  });    
});

Solution

  • Use this current element context to traverse up to common parent using .closest() then use .find()

    $(".process .process--img").click(function () {
        $(this).closest(".process").find(".process--info").toggleClass("process--shown")
    });