How can I get a specific number child using CSS?

前端 未结 2 1301
北海茫月
北海茫月 2020-11-28 18:40

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

相关标签:
2条回答
  • 2020-11-28 18:50

    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.

    0 讨论(0)
  • 2020-11-28 19:13

    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*/ }
    
    0 讨论(0)
提交回复
热议问题