Reputation: 55
I am trying to append different colors to some text:
var s = ["red", "green"];
for (i=0; i < s.length; i++) {
$(".colors").append("<span>TEXT </span>").css("color", s[i]);
}
The output of both spans is green, but my intention was that the first one is going to be red and only the second one green. What am I doing wrong?
Upvotes: 1
Views: 105
Reputation: 144659
That's because append
returns the selected element not the appended element, so you are modifying color of the .colors
element(s) not the appended elements, the last color wins and descendant elements inherit the color property.
$("<span>TEXT</span>").css("color", s[i]).appendTo(".colors");
Upvotes: 6