Manoj Singh
Manoj Singh

Reputation: 7707

How to add class on td trough Jquery

I have below html

<table class="Newuser" cellspacing="0" cellpadding="0" border="0" id="ctl00_ContentPlaceHolder2_CreateUserWizard1">
<tr>
    <td>
        <table>
            <tr>
                <td>
                </td>
                <td>
                </td>
            </tr>
        </table>
    </td>
</tr>
<tr>
    <td>
        <table>
            <tr>
                <td>
                </td>
                <td>
                </td>
            </tr>
        </table>
        </td>
    </tr>
</table>

Now I want to add a class on runtime through Jquery so that my update code will become as below. I want to add a class on second tr first td whose main class is "Newuser"

<table class="Newuser" cellspacing="0" cellpadding="0" border="0" id="ctl00_ContentPlaceHolder2_CreateUserWizard1">
<tr>
    <td>
        <table>
            <tr>
                <td>
                </td>
                <td>
                </td>
            </tr>
        </table>
    </td>
</tr>
<tr>
    <td>
        <table>
            <tr>
                <td class="buttonClose">
                </td>
                <td>
                </td>
            </tr>
        </table>
        </td>
    </tr>
</table>

Please suggest!

Upvotes: 1

Views: 14940

Answers (3)

nickf
nickf

Reputation: 546045

First of all, I have to say that nested tables are 100% awful. Please reconsider your design.

Ok, now that's out of my system, try this:

$("table.Newuser > tbody > tr:eq(1) table td:eq(0)").addClass("buttonClose")

To select the first row of the Newuser table, you need to use these > children rules, including the tbody, otherwise the "second tr" is actually the first tr of the table in the first row, if you know what I mean.

Some browsers add a <tbody> element automatically to tables without them, others don't, and I think this query might not work in those browsers. You should always add a tbody element to your tables. (And never nest them, either!!)

Upvotes: 5

joebert
joebert

Reputation: 2663

$('#ctl00_ContentPlaceHolder2_CreateUserWizard1 > tr').filter(':nth-child(2)').find('td:first').addClass('buttonClose');

Upvotes: 0

Related Questions