jonathanGB
jonathanGB

Reputation: 1540

Dynamic class not being inserted when supposed to

Basically, I want to add a class to every list item, and each class has to be specific to a "house". So, I've created an array to store all the houses, and everything seems fine. The problem seems to be in the last for loop, where the classes are added, and their value are the ones store in the previous houseColours[] array: however, when I look in the console, the classes are not inserted.

Even more weird, if I manually insert a class in the console by doing something like this:

$('li:eq(0)').addClass(houseColours[0]);

... it works just fine. What could be the problem? Thanks.

function chart()
    {
        houseColours = [];
        var html = "<ol start='0'>";
        for (var i = 0; i < shuttle.seats.length; i++)
        {
            if (shuttle.seats[i] == null)
            {
                html += "<li>Empty Seat</li>";
            }
            else
            {
                for (var j = 0, n = PASSENGERS.length; j < n; j++)
                {
                    if (shuttle.seats[i] == PASSENGERS[j].name)
                    {
                        var house = PASSENGERS[j].house;
                        break;
                    }
                }
                houseColours.push(house);

            html += "<li>" + shuttle.seats[i] + ' at ' + house + "</li>";
        }
    }
    html += "</ol>";

    $("#chart").html(html);

    for (var k = 0, banners = houseColours.length; k < banners; k++)
    {
        $('li:eq(k)').addClass(houseColours[k]);
    }
}

Upvotes: 1

Views: 32

Answers (1)

dashtinejad
dashtinejad

Reputation: 6253

In your selector, $('li:eq(k)') the k is part of the selector string, you should use it as a variable (outside of string), like below:

$('li:eq(' + k + ')').addClass(houseColours[k]);

It's better to use .eq method instead of :eq selector, however:

$('li').eq(k).addClass(houseColours[k]);

Upvotes: 1

Related Questions