views:

55

answers:

4

I know to style odd / even table cells using jQuery, but how do i style the 3rd, 4th or 5th element?

<table width="300" border="0" cellspacing="0" cellpadding="0" id="Weekdays">
<thead>
  <tr>
    <td>Week Day</td>
    <td>Short Name</td>
  </tr>
</thead>
<tbody>
  <tr>
    <td>Monday</td>
    <td>Mon</td>
  </tr>
  <tr>
    <td>Tuesday</td>
    <td>Tue</td>
  </tr>
  <tr>
    <td>Wednesday</td>
    <td>Wed</td>
  </tr>
  <tr>
    <td>Thursday</td>
    <td>Thr</td>
  </tr>
  <tr>
    <td>Friday</td>
    <td>Fri</td>
  </tr>
  <tr>
    <td>Saturday</td>
    <td>Sat</td>
  </tr>
  <tr>
    <td>Sunday</td>
    <td>Sun</td>
  </tr>
</tbody>
</table>

How do i do it?

+3  A: 

Using eq():

$('td:eq(5)').css('background','red');

// OR:

$('td').eq(5).css('background','red');

Both of those examples would color the 6th TD element's background in red.

IgalSt
Used this instead$('#Weekdays tbody tr:eq(5)').css('background','#F2C2C2');worked perfectly for me. Thank you.
Roccos
Accept his answer if its the one you used !
RobertPitt
How do i style every 5th alternate cell?????Ex: first 5 then 10th then 15th and so on....
Roccos
Thats a other question... http://jsfiddle.net/dy8h6/
chriszero
just loop them: http://jsfiddle.net/jUzdL/
IgalSt
@chriszero Check my example. It's loop length is the amount of TD/5 while your's is 5 times longer
IgalSt
A: 
$('#Weekdays tbody tr').each(function(i) {
   // Modify the style of element i here
});
theycallmemorty
+1  A: 

You can use .slice() to literally get an element range (though I'm not 100% sure that's what you're after), like this:

$("td").slice(2, 5).css("color", "red");​

You can give it a try here this would select the following elements:

  • <td>Monday</td>
  • <td>Mon</td>
  • <td>Tuesday</td>

So I'm not sure what you mean by the element, here's a version using rows, just swap "td" for "tr" to get this.

Nick Craver
I learn something new every day. That slice function is pretty handy.
Sandro
A: 
$('tr:nth-child(5)').function();

Theres a lot of things you don't know about CS3 :) http://www.w3.org/TR/css3-selectors/

RobertPitt
nth-child(5) selects the 6th child in TD and not the 6th TD
IgalSt
yep, my mistake.
RobertPitt
why the down vote ?
RobertPitt