tags:

views:

70

answers:

4

I have a table, and I want get the first “td” in all rows.

My jquery here:

$("table.SimpleTable tr td:first-child").css('background-color','red');

and my HTML here:

<table class='SimpleTable' border="1" ID="Table1">
        <tr>
            <td>Left</td>
            <td>Right</td>
        </tr>
        <tr>
            <td>Left</td>
            <td>Right</td>
        </tr>
        <tr>
            <td>Left</td>
            <td>Right</td>
        </tr>
        <tr>
            <td>Left</td>
            <td>
                <table border="1" ID="Table2">
                    <tr>
                        <td>AAA</td>
                        <td>AAA</td>
                        <td>AAA</td>
                    </tr>
                </table>
            </td>
        </tr>
        <tr>
            <td>Left</td>
            <td>
                <table border="1" ID="Table3">
                    <tr>
                        <td>BBB</td>
                        <td>BBB</td>
                        <td>BBB</td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>

The problem here it get the first "td" in the nested table of the second "td".

Please help me!

A: 

Normal CSS selectors will work, you were almost spot on. First td in a nested table would be

$('table table tr td:first-child');

To limit the selection only to the second table would be:

$('table table tr td:first-child').filter(':nth(1)');

Live example at jsfiddle

nikc
+1  A: 

try:

$("table.SimpleTable > tbody > tr > td:first-child").css(..);

> only searches in children instead of all descendants. we need tbody as browsers insert that into the table.

example here.

Anurag
Didn't know of jsfiddle, thanks mate!
nikc
jsfiddle is dope :) love it!
Anurag
+1 `tbody`. It's a good idea to add an explicit `<tbody>` to the markup too, to make it clear what's happening and ensure it will still work if you ever serve it as XHTML.
bobince
It work! Thank so much! :)
bobby
@bobby if this worked for you, you can mark the answer as "accepted" using the check mark symbol to the left.
Pekka
A: 
$('table.SimpleTable').find('tr').each(function(){
   $(this).find('td:first').css('backgroundColor', 'red');
});

should do it.

Kind Regards

--Andy

jAndy
find will get all descendants, not just immediate children. you may want `find('> tbody > tr')` there
Anurag
A: 

You need to select immediate/direct children, try this:

$("table.SimpleTable > tr td:first-child").css('background-color','red');

The > allows you to target only the immediate elements

Sarfraz