Iladarsda
Iladarsda

Reputation: 10696

JQuery each loop - do something with currently looped element

I have following .each jQuery loop.

$('.category').each(function(index) {
    if( $('.category > span').parent().next('h2') ) { 

        // get currently looped element which follows the condition
    }

});

How to get currently looped element through .each inside the if statement?

Upvotes: 2

Views: 580

Answers (2)

Matijs
Matijs

Reputation: 3148

$('.category').each(function(index) {
 var that = $(this);
 if( $('.category > span').parent().next('h2') ) { 
  // do something with `that`
 }
});

Cached $(this) to avoid having to look it up every time you use it…

Upvotes: 2

Sarfraz
Sarfraz

Reputation: 382666

How to get currently looped element through .each inside the if statement?

Use:

$(this) // represents current iterated element in wrapped set

Example:

$('.category').each(function(index) {
    if( $('.category > span').parent().next('h2') ) { 
      $(this).css('color', 'red');
    }
});

Note that you could also get DOM object instead of jQuery object by using this keyword.

Upvotes: 4

Related Questions