How to set incremental CSS classes in each Table Cell with jQuery?

Posted by Mark Rapp on Stack Overflow See other posts from Stack Overflow or by Mark Rapp
Published on 2010-04-30T13:35:54Z Indexed on 2010/04/30 13:37 UTC
Read the original article Hit count: 328

Filed under:
|
|

I have a table populated via a DB and it renders like so (it could have any number of columns referring to "time", 5 columns, 8 columns, 2 columns, etc):

<table id="eventInfo">
<tr> 
     <td class="name">John</td> 
     <td class="date">Dec 20</td> 
     <td class="**time**">2pm</td>
     <td class="**time**">3pm</td>
     <td class="**time**">4pm</td>
     <td class="event">Birthday</td>                
 </tr>
 <tr> 
     <td class="name">Billy</td> 
     <td class="date">Dec 19</td> 
     <td class="**time**">6pm</td>
     <td class="**time**">7pm</td>
     <td class="**time**">8pm</td>
     <td class="event">Birthday</td>         
</tr>  

With jQuery, I'd like to go through each Table Row and incrementally set an additional class-name on only the Table Cells where "class='time'" so that the result would be:

John Dec 20 2pm 3pm 4pm Birthday Billy Dec 19 6pm 7pm 8pm Birthday

I've only been able to get it to count all of the Table Cells where "class='time'" and not each set within its own Table Row. This is what I've tried with jQuery:

$(document).ready(function() {

     $("table#eventInfo tr").each(function() {   
            var tcount = 0;
            $("td.time").attr("class", function() {
              return "timenum-" + tcount++;
            })
            //writes out the results in each TD
            .each(function() {
              $("span", this).html("(class = '<b>" + this.className + "</b>')");
            });    

        });

    });

Unfortunately, this only results in:

<table id="eventInfo">
<tr> 
     <td class="name">John</td> 
     <td class="date">Dec 20</td> 
     <td class="**time** **timenum-1**">2pm</td>
     <td class="**time** **timenum-2**">3pm</td>
     <td class="**time** **timenum-3**">4pm</td>
     <td class="event">Birthday</td>                
 </tr>
 <tr> 
     <td class="name">Billy</td> 
     <td class="date">Dec 19</td> 
     <td class="**time** **timenum-4**">6pm</td>
     <td class="**time** **timenum-5**">7pm</td>
     <td class="**time** **timenum-6**">8pm</td>
     <td class="event">Birthday</td>         
</tr>  

Thanks for your help!

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about css