Toran Billups Toran Billups - 2 months ago 8
HTML Question

How to addClass to the first td in every tr inside a table using jQuery

I'm trying to add a class to the first td inside a tr within a specific class. But for some reason it adds this class only to the first td in the first tr -not the first td in each tr

$("#appendTD").find("#gridFormInformation").children(0).children().each(
function() {
if ($("#appendTD").find('tr').filter(function() { return $(this).attr('class') == 'ui-widget-content ui-subtblcell'; }).children("td:eq(0)").addClass("leftbord"));
}
);


But when I alter the above by removing the ""td:eq(0)" it adds this class to each td in each tr ... so what am I doing wrong?

Example of the markup below

<td id="appendTD">
<table id="gridFormInformation">
<tbody>
<tr><th>1</th><th>2</th><th>3</th></tr>
<tr class="ui-widget-content ui-subtblcell"><td>1</td><td>2</td><td>3</td></tr>
<tr class="ui-widget-content ui-subtblcell"><td>1</td><td>2</td><td>3</td></tr>
<tr class="ui-widget-content ui-subtblcell"><td>1</td><td>2</td><td>3</td></tr>
</tbody>
</table>
</td>

Answer

It looks to me like you're using a complicated manual way to find the tds you want to add the class to. I believe it would be easier to use jQuery selectors to find your tds.

Replace

$("#appendTD").find("#gridFormInformation").children(0).children().each(
            function() {
                if ($("#appendTD").find('tr').filter(function() { return $(this).attr('class') == 'ui-widget-content ui-subtblcell'; }).children("td:eq(0)").addClass("leftbord"));
            }
        );

with

$("#gridFormInformation tr.ui-widget-content.ui-subtblcell").find("td:first").addClass("leftbord");

This would find all the trs and for each tr find the first td and add the class to that.