1

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?

1 Answer 1

6

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");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.