272

I have a table whose tds are created dynamically. I know how to get the first and last child but my question is:

Is there a way of getting the second or third child using CSS?

Paulie_D
  • 107,962
  • 13
  • 142
  • 161
Satch3000
  • 47,356
  • 86
  • 216
  • 346

2 Answers2

402

For modern browsers, use td:nth-child(2) for the second td, and td:nth-child(3) for the third. Remember that these retrieve the second and third td for every row.

If you need compatibility with IE older than version 9, use sibling combinators or JavaScript as suggested by Tim. Also see my answer to this related question for an explanation and illustration of his method.

Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • 19
    Don't forget that this works only with CSS 3 selectors (in other words, not in versions of IE prior to 9). – zneak Apr 14 '11 at 14:31
  • 1
    [Soon a concern of the past](https://www.microsoft.com/en-us/WindowsForBusiness/End-of-IE-support) ... [My feelings on this](https://media.giphy.com/media/Ic97mPViHEG5O/giphy.gif). – Clarus Dignus Jan 22 '16 at 02:29
  • 3
    As a general solution, `td:nth-of-type(3)` is better. `td:nth-child(3)` will match an element that is **both** a `td` **and** the third child of its parent, **regardless of the element types of its two previous siblings**. `td:nth-of-type(3)` will get the third `td`, **regardless of how many non-`td` elements are before it**. If there are no non-`td` elements before the one you want, both selectors will match the same thing. – CJ Dennis Mar 09 '17 at 02:04
233

For IE 7 & 8 (and other browsers without CSS3 support not including IE6) you can use the following to get the 2nd and 3rd children:

2nd Child:

td:first-child + td

3rd Child:

td:first-child + td + td

Then simply add another + td for each additional child you wish to select.

If you want to support IE6 that can be done too! You simply need to use a little javascript (jQuery in this example):

$(function() {
    $('td:first-child').addClass("firstChild");
    $(".table-class tr").each(function() {
        $(this).find('td:eq(1)').addClass("secondChild");
        $(this).find('td:eq(2)').addClass("thirdChild");
    });
});

Then in your css you simply use those class selectors to make whatever changes you like:

table td.firstChild { /*stuff here*/ }
table td.secondChild { /*stuff to apply to second td in each row*/ }
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Tim
  • 7,660
  • 3
  • 30
  • 33
  • 2
    You can take the CSS3 selectors in my answer or the CSS2 selectors in yours and drop them right into jQuery and they'll work naturally in IE6. No need to jump through all these extra hoops to add the classes. – BoltClock Mar 21 '12 at 18:27