Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I applying 1 class from an array to each li in order?

Tags:

html

jquery

css

html

<ul class="logoUl">
    <li class="orange"></li>
    <li class="blue"></li>
    <li class="green"></li>
    <li class="pink"></li>
</ul>

SCRIPT

if (selectedCategory == 'currentAll') {

    var strString = "orange,blue,green,pink";
    var strArray = strString.split(',');

    $.each(strArray, function (index, value) {
        $("ul.logoUl > li").addClass(value)
    });
}

there are 4 li's in the ul.logoUL making an image liek thisenter image description here Some times the logo gets a background color which will reset the colors to gray like so

currently my code does this doesnt reset the colors backenter image description here

Question:

How can iterate through li's one at a time while adding one class at a time in hopes to gain the original colors scheme via classes?

like image 752
Armeen Harwood Avatar asked Jun 22 '12 05:06

Armeen Harwood


1 Answers

var strString = "orange,blue,green,pink",
    strArray = strString.split(',');

$("ul.logoUl > li").each(function (index, value) {
    $(this).addClass(strArray[index]);
});

DEMO

Without loop:

var strString = "orange,blue,green,pink",
    strArray = strString.split(',');

$("ul.logoUl > li").addClass(function (index) {
    return strArray[index];
});

DEMO

Note

As you're changing class to each li to give them similar background sometimes, so when you want to give them their original color scheme again, it would be better to remove previously assigned color class first and then assign original class again like following:

var strString = "orange,blue,green,pink",
    strArray = strString.split(',');

$("ul.logoUl > li")
    .removeClass() // first remove previous class
    .addClass(function (index) { // then add new class
        return strArray[index];
    });

DEMO

like image 159
thecodeparadox Avatar answered Nov 15 '22 03:11

thecodeparadox