Select the first TD in each row of w / jQuery

How to style each first cell of each table row?

$("#myTable tr td:first").addClass("black"); 
+52
jquery
27 '11 at 16:42
source share
5 answers

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

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

The :first pseudo-class actually selects the first item that was returned in your list. For example, $('div span:first') will return only the very first run under the first div that was returned.

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

When you used :first , it returned only the first cell of the first row that was selected.

See the jQuery documentation for more information:

+99
May 27 '11 at 16:45
source share

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

 $("#myTable tr td:first-child").addClass("black"); 
+9
May 27 '11 at 16:45
source share
 $("#myTable tr").find("td:first").addClass("black"); 
+5
May 27 '11 at 16:46
source share

like this:

 $("#myTable tr").each(function(){ $(this).find('td:eq(0)').addClass("black"); }); 
+4
May 27 '11 at 16:45
source share

Try:

 $("#myTable td:first-child").addClass("black"); 
+3
May 27 '11 at 16:46
source share



All Articles