Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning ODD/EVEN Class to span with Jquery/javascript

i just stuck up with assigning ODD/EVEN Class to span with Jquery.

QUESTION UPDATED

I need to add class to span inside col div as "odd"/"even" . check the commented class name and order of execution & i need to assign in this way.

Expected Output: Class name are in comments

<section>

    <div class="col">
        <span></span> <!-- ODD --> (1)
        <span></span> <!-- ODD --> (5)
        <span></span> <!-- EVEN--> (8)
        <span></span> <!-- ODD--> (10)
        <span></span><!-- EVEN--> (11)
    </div>

    <div class="col">
        <span></span><!-- EVEN--> (2)
        <span></span><!-- ODD-->  (6)
        <span></span><!-- EVEN--> (9)
    </div>

    <div class="col">
        <span></span><!-- ODD --> (3)

    </div>
    <div class="col">
        <span></span><!-- EVEN--> (4)
        <span></span><!-- ODD-->  (7)
    </div>

</section>
like image 970
Parthi04 Avatar asked Apr 16 '26 09:04

Parthi04


1 Answers

Look at this working jsFiddle.

$(function(){
    $('.col > span:odd').addClass('odd');
    $('.col > span:even').addClass('even');
});

Use .col > to make sure you're not effecting other spans on the page.

I've updated jsFiddle according to the new requirement.

$(function(){
    var currentClass = 'odd';
    var currentRow = 0;
    var updated = true;

    while(updated){
        updated = false;
        $('.col').each(function(index,value){
            var currentSpans = $(value).find('span');
            if(currentRow < currentSpans.length){
                currentSpans.eq(currentRow).addClass(currentClass);
                currentClass = (currentClass == 'odd') ? 'even':'odd';
                updated = true;
            }
            if($(value).is(':last-child')){
                currentRow++;
            }
        })
    }
});
like image 92
Yotam Omer Avatar answered Apr 17 '26 22:04

Yotam Omer