Question

I've got an example here of a typical chunk of JavaScript (code that would apply a background style class to an alternating odd or even row in a table). I'm trying to rewrite this in CoffeeScript in my attempt to learn that. The CoffeeScript range syntax is different and more Ruby-esque. I'd really appreciate an example of how you would do this?

   function alternate(id){ 
     if(document.getElementsByTagName){  
       var table = document.getElementById(id);   
       var rows = table.getElementsByTagName("tr");   
       for(i = 0; i < rows.length; i++){           
     //manipulate rows 
         if(i % 2 == 0){ 
           rows[i].className = "even"; 
         }else{ 
           rows[i].className = "odd"; 
         }       
       } 
     } 
    }

Update

I'm using JQuery and trying this but it doesn't work (it makes all rows #efefef):

$(document).ready ->
    rowCount = $('tbody tr')
    for row in rowCount        
        if row.length % 2 == 0
            $('tbody tr').css('background-color', '#363636')
        else
            $('tbody tr').css('background-color', '#efefef')
Was it helpful?

Solution

A little more concise:

for row, i in $('tbody tr')
  color = if i % 2 is 0 then '#363636' else '#efefef'
  $(row).css 'background-color', color

OTHER TIPS

You may also be interested in the even / odd meta selectors provided by jquery

$('tbody tr:even').css 'background-color', '#363636'
$('tbody tr:odd').css 'background-color', '#efefef'

If your end goal is just to apply a different style to odd/even rows, you can try this:

// CSS file

#myTable tr:nth-child(even) { background-color: #363636; }
#myTable tr:nth-child(odd)  { background-color: #efefef; }

No JS here, just plain CSS, which is good since styling is a presentation concern.

However it only works in (relatively) modern browsers: IE 9+, Firefox 4+, Chrome...

Try for row, i in rows, where i holds the loop counter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top