Nathan Campos
Nathan Campos

Reputation: 29497

Change The Classes Of List Elements

I want to change the class of each list(#list) item to the correspondent one at an Array. I have a list that is like this:

<ul id="list">
    <li>Banana</li>
    <li>Apple</li>
    <li>Pear</li>
    <li>Strawberry</li>
    <li>Lemon</li>
</ul>

And I have this array:

["ban", "appl", "per", "straw", "lemn"]

What I want is that jQuery .addClass() function to change each item with the class in the order as they are on the Array. To result into this:

<ul id="list">
    <li class="ban">Banana</li>
    <li class="appl">Apple</li>
    <li class="per">Pear</li>
    <li class="straw">Strawberry</li>
    <li class="lemn">Lemon</li>
</ul>

How can I do it?

Upvotes: 0

Views: 113

Answers (4)

Paul
Paul

Reputation: 141829

$.each(myArray, function(i, value){
        $('#list li').eq(i).addClass(value);
    }
);

Upvotes: 1

bcoughlan
bcoughlan

Reputation: 26627

var myArray = ["ban", "appl", "per", "straw", "lemn"];
$("#list > li").each(function(index) {
    $(this).addClass(myArray[index]);
});

Upvotes: 2

Dan Tao
Dan Tao

Reputation: 128317

This should work for you:

var classes = ["ban", "appl", "per", "straw", "lemn"];

$('#list > li').addClass(function(index) {
  return classes[index];
});

You can see the documentation for this overload (the one that takes a function(index, currentClass) callback) on the jQuery website.

Upvotes: 4

Stefan Kendall
Stefan Kendall

Reputation: 67802

$('#list > li').each(function(i){
    $(this).addClass( myArray[i] );
});

Upvotes: 2

Related Questions