remixdesign remixdesign - 5 months ago 14
jQuery Question

Better way to use jquery each

I have a parent div containing 5 children. Each is a progress point with three options - Past - Present - Future. The are in order so for example if the middle div has the class present, the previous 2 should be past, and the 2 following should be future.

In my example the jquery ive made works - I am just 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");
}
});

Answer

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(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)