Select first TD in every row w/ jQuery

Jquery

Jquery Problem Overview


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

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

Jquery Solutions


Solution 1 - Jquery

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:

Solution 2 - Jquery

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");

Solution 3 - Jquery

like this:

$("#myTable tr").each(function(){
    $(this).find('td:eq(0)').addClass("black");
});

Solution 4 - Jquery

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

Solution 5 - Jquery

Try:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsantaView Question on Stackoverflow
Solution 1 - JqueryDevin BurkeView Answer on Stackoverflow
Solution 2 - Jquerynathan gonzalezView Answer on Stackoverflow
Solution 3 - JqueryTeneffView Answer on Stackoverflow
Solution 4 - JquerybevacquaView Answer on Stackoverflow
Solution 5 - JquerystefgosselinView Answer on Stackoverflow