Select first TD in every row w/ jQuery

前端 未结 5 2070
轮回少年
轮回少年 2020-12-23 19:10

How do I assign a style to every first cell of every row in a table?

$(\"#myTable tr td:first\").addClass(\"black\");
相关标签:
5条回答
  • 2020-12-23 19:21
    $("#myTable tr").find("td:first").addClass("black");
    
    0 讨论(0)
  • 2020-12-23 19:26

    you were pretty close, i think all you need is :first-child instead of :first, so something like this:

    $("#myTable tr td:first-child").addClass("black");
    
    0 讨论(0)
  • 2020-12-23 19:26

    Try:

    $("#myTable td:first-child").addClass("black");
    
    0 讨论(0)
  • 2020-12-23 19:29

    Use the :first-child pseudo class instead of :first.

    $("#myTable tr td:first-child").addClass("black");
    

    The :first pseudo class actually selects the first element that was returned in your list. For example, $('div span:first') would return only the very first span under the first div that happened to be returned.

    The :first-child pseudo class selects the first element under a particular parent, but returns as many elements as there are first children. For example, $('table tr td:first-child') returns the first cell of every single row.

    When you used :first, it was returning only the first cell of the first row that happened to be selected.

    For more information, consult the jQuery documentation:

    • http://api.jquery.com/first-selector/
    • http://api.jquery.com/first-child-selector/
    0 讨论(0)
  • 2020-12-23 19:35

    like this:

    $("#myTable tr").each(function(){
        $(this).find('td:eq(0)').addClass("black");
    });
    
    0 讨论(0)
提交回复
热议问题