Sunday, May 1, 2011

How to select table cells without selecting nested table cells in jQuery

I want to select only the first level of 'td' elements in a table and not the cells of any nested tables. eg:

<table id="Outer">
    <tr>

        <td> --this one
        </td> 

        <td> --this one
            <table>
                <tr>
                    <td></td> -- but not this one or any deeper nested cells
                </tr>
            </table>
        </td>

    </tr> 
</table>

(and yes in prod code i would include tbody, thead...)

From stackoverflow
  • Give the outermost table an id of "Outer":

    $("table#Outer > td").text("selected");
    
    rizzle : didn't seem to work for me
    tvanfosson : TD is not an immediate child of a TABLE.
    rizzle : you have to do $("table#Outer > tbody > tr > td").text("selected"); even if i don't have tbody in my source the browser seems to put it in automatically (FF3)
  • I'd use the children selector, which only selects the immediate children matching the expression. To make it easy to select just the outer table, I'd give it a name. NOTE: this won't work with your sample as I've added in the selectors for thead, tbody, and tfoot as you indicate you will have in production. Adjust accordingly for your sample.

    $('table#namedTable').children('tbody,thead,tfoot')
                         .children('tr')
                         .children('td')
    
    rizzle : perfect, thanks!
    rizzle : oddly enough the browser automatically added tbody (FireFox) and so the code did work even if i didn't have tbody in the source.
    karim79 : +1, excellent answer - On first glance, this problem seems quite trivial, but that's not the case.

0 comments:

Post a Comment