Best way to use jquery each

advertisements

I have a parent div containing 5 children (.item). Each child div is a progress point that can have three options: .past - .current - .future. The divs are in order (left to right) so if the middle div (3) has the class .current, the previous 2 should be past, and the 2 following that div should be future.

In my example I've used jQuery each to add the proper classes and it works. However, I am curious if there is a better, more concise, way to achieve this? (I'm sure there is!)

Fiddle: https://jsfiddle.net/remix1201/uxgv62z9/

HTML:

<div class="series-set-options">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
</div>

JS:

var flowStep = 3;

$(".series-set-options").children().each(function(i){
    if (flowStep > i){
        $(".series-set-options").children().eq(i).addClass("past");
    }
    if ( flowStep == i){
        $(".series-set-options").children().eq(i).addClass("current");
    }
    if (flowStep < i){
        $(".series-set-options").children().eq(i).addClass("future");
    }
});


You could use :eq() and then prevAll() and nextAll() DEMO

$(".item:eq(2)").addClass('current').prevAll('.item').addClass('past');
$(".item:eq(2)").nextAll('.item').addClass('future');

Or as @Tushar suggested single-line DEMO

$(".item")
    .eq(flowStep)                         // flowStep = 2
    .addClass('current')                  // eq(2)
    .prevAll('.item').addClass('past')    // prevAll of eq(2)
    .end()                                // eq(2) end = go back to prev context
    .nextAll('.item').addClass('future'); // nextAll of eq(2)