How to get colors in order on the divs using arrays

I want these colors to loop in order of colors given. But it gives me only green on all my divs.

var colors = ["red", "blue", "green"];
for (var i = 0; i < colors.length; i++) {
  $("div").each(function() {
    $("div").css({
      'background-color': colors[i]
    });
  });
}

HTML:

<div>A</div>
<div>B</div>
<div>C</div>

solution

You can actually simplify your code and just use the index from the .each() method. It’s worth pointing out that the first parameter that is passed in the .each() method is the index, and the second is a reference to the current element.

If you have more than three items, you can also use i % colors.length in order to start back at the beginning of the array after the third index.

Updated Example

var colors = ["red", "blue", "green"];
$("div").each(function(i) {
  $(this).css('background-color', colors[i % colors.length]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>A</div>
<div>B</div>
<div>C</div>
<div>D</div>
<div>E</div>