Reputation: 35691
I simply try to assign a background color to each div. it looks simple but it doesn't work.
var divElements = $("div");
var colorArray =["444", "344", "345", "472", "837", "043", "345", "472", "837", "043"];
for (var i=0; i< divElements.length; i++){
divElements[i].css("background","#"+colorArray[i])
}
I also tried to use jQuery's each
$("div").each(function(i) {
divElements[i].css("background","#"+colorArray[i])
})
How do code this in javaScript generic "for loop" and jQuerys .each()
Upvotes: 0
Views: 923
Reputation: 21727
Here's what you do:
var colors = ["#444", "#344", etc.];
$("div").each(function (i)
{
$(this).css("background-color", colors[i]);
});
You might get a small speed-gain if you skip converting "this" into a jQuery object and just use the JavaScript native API, like so:
this.style.backgroundColor = colors[i];
Also, you might want to assign a default color, if you've got more DIV-elements than entries in your array:
this.style.backgroundColor = colors[i] || "#fff";
The native approach:
var colors = ["#444", "#344", etc.],
divElements = document.getElementsByTagName("div"),
i = divElements.length;
while (i)
{
// This is a reverse while-loop and runs a lot faster than other methods.
// This means that the first div element will get assigned the value of the
// last entry in the "colors"-array. If this breaks your brain, use the
// Array.reverse() function on the "colors"-array declaration :)
i--;
divElements[i].style.backgroundColor = colors[i] || "#fff";
}
Upvotes: 3
Reputation: 625037
$("div").each(function(i, val) {
$(this).css("background", "#" + colorArray[i]);
});
You have to watch out for exceeding the bounds of colorArray though (ie if you get too many divs). Possibilities include stopping when you hit the max:
$("div").each(function(i, val) {
if (i > colorArray.length) {
return false; // breaks $.each() loop
}
$(this).css("background", "#" + colorArray[i]);
});
or cycle through them:
$("div").each(function(i, val) {
$(this).css("background", "#" + colorArray[i & colorArray.length]);
});
Not sure why you'd want to do it as Javascript but:
var divElements = document.getElementsByTagName("div");
var colorArray =["444", "344", "345", "472", "837", "043", "345", "472", "837", "043"];
for (var i=0; i< divElements.length; i++){
divElements[i].style.backgroundColor = '#' + colorArray[i];
}
Upvotes: 4
Reputation: 105878
try background-color
instead of background
, which is the shorthand for multiple other CSS rules.
divElements[h].css("background-color","#"+colorArray[h])
Upvotes: 0