Reputation: 29497
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
Reputation: 141829
$.each(myArray, function(i, value){
$('#list li').eq(i).addClass(value);
}
);
Upvotes: 1
Reputation: 26627
var myArray = ["ban", "appl", "per", "straw", "lemn"];
$("#list > li").each(function(index) {
$(this).addClass(myArray[index]);
});
Upvotes: 2
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
Reputation: 67802
$('#list > li').each(function(i){
$(this).addClass( myArray[i] );
});
Upvotes: 2