2

Say I have a table:

<table id="#myTable">
    <tr>
        Section 1
        <td>
            <table>
                <tr>
                    Sub 1
                    <td>Sub2</td>
                    Sub3
                    <td>Sub 4</td>
                </tr>
            </table>
        </td>

        <td>Section 2</td>
    </tr>
</table>

How do I make a jQuery selector for a function that finds the td containing Sub4 and changes its color to red without affecting the background color of all the other ones?

I tried:

$("#myTable td:contains('Sub 4')").css('background','red');

But it appears to think that the outer table also catches the event. How do I get a reference to just the innermost td?

Bojangles
  • 99,427
  • 50
  • 170
  • 208
Rolando
  • 58,640
  • 98
  • 266
  • 407
  • 3
    you might wanna check your mark-up again. i tried to edit but couldn't understand it – Joseph Mar 19 '12 at 22:00
  • 3
    possible repeat question : http://stackoverflow.com/questions/3787924/select-deepest-child-in-jquery – Evan Mar 19 '12 at 22:01
  • 1
    Erm... as far as I can tell that markup is invalid. you should only have other elements (like `` and ``) within a `` but I see you have the text "Section 1" directly before the first ``? Fix that problem first... – nzifnab Mar 19 '12 at 22:04
  • `id` should be `"myTable"` not `"#myTable"`. You are missing ``s too – brian_d Mar 19 '12 at 22:12
  • 1
    oh duh, not sure how i missed that. it should be id="myTable" (your jquery selector looks right?) but also the markup itself is sorta weird. – nzifnab Mar 19 '12 at 22:17

2 Answers2

0

By deepest, I'm guessing you actually mean the LAST td in a particular row:

$('#mytable tr td:last').css('background', 'red');
                 ^^^^^-- add that.
Marc B
  • 356,200
  • 43
  • 426
  • 500
  • This is correct if he wants last, but his looked right if he wants the td containing 'Sub 4' (regardless of ordinal position) – nzifnab Mar 19 '12 at 22:23
0

You have assigned an id in wrong way

<table id="#myTable">

should be

<table id="myTable">

If this is your table

<table id="myTable" class="cls" border='1'>
    <tr>
        <td>Section 1</td>
        <td>Sub 1</td>
    </tr>
    <tr>
        <td>Sub2</td>
        <td>Sub3</td>
    </tr>
    <tr>
        <td>Sub 4</td>
    </tr>
    <tr>
        <td>Section 2</td>
    </tr>
</table>​

then you can use

$("#myTable tr td:contains('Sub 4')").css('background','red');

to apply red background color to only td containning "Sub 4".

A fiddle is here.

The Alpha
  • 143,660
  • 29
  • 287
  • 307