Kim
Kim

Reputation: 1156

Add class to the closest element in a loop

Thing is I am having a Facebook like button (created with the API not the regular one) inside each of the elements, and needs to check its status before I can add class "liked" or "unliked". So all the div's with class "item" is created in a PHP loop. And also I understand its not good to run the script several times in a loop. But I need to get further in the testings here :)

 <div class="item">
   <span class="status">
     <div class="like_button"></div>
   </span>
   <script>  
     $(this).closest('span').find('.like_button').addClass('liked')
   </script>
 </div>

 <div class="item">
   <span class="status"> 
     <div class="like_button"></div>
   </span>
   <script>  
     $(this).closest('span').find('.like_button').addClass('liked')
   </script>
 </div>

 <div class="item">
    <span class="status">
       <div class="like_button"></div>
    </span>
    <script>  
      $(this).closest('span').find('.like_button').addClass('liked')
    </script>
 </div>

Upvotes: 0

Views: 1083

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

I think what you looking for is

$('.item .like_button').addClass('liked');

Upvotes: 0

Gabe
Gabe

Reputation: 50493

Not sure if this is what you're asking for or not.

$('.item').each(function(){
    $(this).find('.like_button').addClass('liked');
});

Upvotes: 1

Related Questions