0

Can you please take a look at this Demo and let me know how to fix the issue on this code?

<div id="out"></div>

<script>
$(document).ready(function () {
    var colors = new Array("#FFF", "#CCC", "#7FFF00");
    for (var i = 0; i < colors.length; i++) {
        $("#out").append('<div class="box"></div>');
        $(".box").css("background-color",colors[0]);
    }
});
</script>

what I am trying to do is generating div elements based on an array length and set the background of them from the colors array

Thanks

2 Answers 2

2

The problem is, inside the loop, you are targetting all .box elements instead of targetint the element which was recently added.

You can use .appendTo() instead to return the recently added element and use that reference to make the css changes

$(document).ready(function () {
    var colors = new Array("#FFF", "#CCC", "#7FFF00");
    for (var i = 0; i < colors.length; i++) {
        var $el = $('<div class="box">1</div>').appendTo("#out");
        $el.css("background-color", colors[i]);//also need to use the index of the array instead of the hard coded 0
    }
});

Demo: Fiddle

Also try

jQuery(function ($) {
    var colors = new Array("#FFF", "#CCC", "#7FFF00");
    $.each(colors, function (i, color) {
        var $el = $('<div class="box">1</div>').appendTo("#out");
        $el.css("background-color", color);
    })
});

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

3 Comments

Wow! Thanks Arun, this was supper fast! I need 10 more minutes to accept your reply!
just can you please let me know why did you used appendto instead of append?
@user3674990 because .append() returns the reference to the #out element which is not what we wants.... while .appendTo() returns the reference to the newly created element which can be used for further modification.
1

You should use i no 0

$(".box").css("background-color",colors[i]);

1 Comment

Thanks C-link but this just generate boxes with one color(last code from the array)

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.