ultimatum ultimatum - 3 months ago 7
jQuery Question

How to add following classes to the elements 'li', using method 'map'

Using method 'map' add following classes to the elements 'li' of each list 'ul': 1-st - 'sel', 2-nd - 'sel2', 3-rd - 'sel3', 4-th - 'sel'...

$("li").map(function() {

var replacement = $( "<li>" ). $( this ).get( 0 );
if ( index === 0,4 ) {
$( replacement ).addClass("sel");
}
if ( index === 1,4 ) {
$( replacement ).addClass("sel1");
}
if ( index === 2,5 ) {
$( replacement ).addClass("sel2");
}
return replacement;
});

Answer

Use each instead of map, because map is completly wrong for this task. And you can shorten your code a bit. ;)

$("li").each(function(i) {
    var replacement = $(this),
        index = i > 0 && i < 3 ? ++i : '';

    replacement.addClass("sel" + index);
});
.sel  { color: red; }
.sel2 { color: green; }
.sel3 { color: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>

Or with map, beacuse wished:

$("li").map(function(i) {
    var replacement = $(this),
        index = i > 0 && i < 3 ? ++i : '';

    replacement.addClass("sel" + index);
});
.sel  { color: red; }
.sel2 { color: green; }
.sel3 { color: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>

Comments