Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery modify elements in each loop

Using jquery, I want to loop all elements having the class "item" and apply different background colors according to the index of the element.

mapcolor is an array of colors (length = number of elements having "item" class)

$.each($(".item"), function(i,e){
$("#"+e).css("background-color",mapcolor[i]);
});

$("#"+e) selector doesn't work as expected, neither $("#"+e.id) ... Something's wrong with my selector. Any idea?

like image 552
Abspirit Avatar asked May 26 '26 06:05

Abspirit


1 Answers

use .each() method instead and you have to be in the context with $(this):

$(".item").each(function(i){
  $(this).css("background-color",mapcolor[i]);
});

Yet a better way is:

$(".item").css("background-color",function(){
    return mapcolor[$(this).index()];
});

make use of .css() method and pass a callback function to return the value.

A test is below:

var mapcolor = ['green', 'red', 'yellow'];

$(".item").css("background", function() {
  return mapcolor[$(this).index()];
});
div{height:10px;}
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
like image 86
Jai Avatar answered May 27 '26 21:05

Jai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!