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

    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)
        });
    }
    

    ul.logoUL has 4 li, which makes the image lek this enter image description here Several times the logo gets a background color that will reset the color to graylike so

    Currently, my code is doing this reset colors back enter image description here

    Question:

    How to scroll through lione at a time, adding one class at a time in the hope of getting the original color scheme through the classes?

    +5
    source share
    2 answers
    var strString = "orange,blue,green,pink",
        strArray = strString.split(',');
    
    $("ul.logoUl > li").each(function (index, value) {
        $(this).addClass(strArray[index]);
    });
    

    Demo

    Without a loop:

    var strString = "orange,blue,green,pink",
        strArray = strString.split(',');
    
    $("ul.logoUl > li").addClass(function (index) {
        return strArray[index];
    });
    

    Demo

    Note

    , class li, background, , , class , class :

    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

    +6

    if (selectedCategory == 'currentAll') {
    
        var strString = "orange,blue,green,pink";
        var strArray = strString.split(',');
    
        $.each(strArray, function (index, value) {
            $("ul.logoUl > li").eq(index).addClass(value)
        });
    }
    

    : http://jsfiddle.net/joycse06/j4qqS/

    +2

    All Articles