How do target some elements inside if {}

If I have this:

  if('li').offset().top > $('.current').offset().top){
    $(this).addClass('push');
  }

How do i target the elements that match the criteria inside the if statement??? This is a problem i pretty often encounter, as I can’t use $(this)??

What I want to do is that if some of the list items have a higher offset top then the one with the class .current , I want to add a class to them.

You can iterate through collection of elements and check offset for each of them:

$('li').each(function(){
    // now $(this) contains current element in collection
    // so you can check its offset and add class
    if ($(this).offset().top > $('.current').offset().top){
        $(this).addClass('push');
    }
});
2 Likes

Thanks, worked fine=)

a little improvement to my previous code:

var currentTop = $('.current').offset().top;
$('li').each(function(){
    if ($(this).offset().top > currentTop){
        $(this).addClass('push');
    }
});

this should execute a little bit faster, i guess :slight_smile:
because there is no need to search for .current in DOM every time

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.