Getting the element index in a SASS @each loop
I wonder why this isn’t in the default SASS documentation. If you want to iterate over a list in SASS using @each, how do you get the index of the current item? For example, to make odd-even colored table rows?
$list: foo, bar, baz;
@each $item in $list {
.#{$item} {
// Right, so we want to see if the item index is
// odd or even, but how do we get the index?
}
}
Turns out this is not possible with @each
, but you can use a combination of a @for
loop and the little-used nth
function:
$list: foo, bar, baz;
@for $i from 1 through length($list) {
$item: nth($list, $i);
.#{$item} {
@if $i % 2 == 0 {
background: red;
} @else {
background: blue;
}
}
}
Note that lists in SASS start at 1, not at zero.
zaus
Are you sure you can’t use `index({list}, {key})`? As in:
hay
Unfortunately that approach fails whenever there are two identical values in the list.