views:

63

answers:

1

Hi,

is there a way to directly select all 'inner' table cells (<td> elements) of a table (i.e. all cells except the ones in the first and last row and column) using a jquery selector expression?

Thanks

Martin

+4  A: 

You can use :not() with the :first-child and :last-child selectors, like this

$('table td:not(:first-child, :last-child)')

To exclude first/last rows as well:

$('table tr:not(:first-child, :last-child) td:not(:first-child, :last-child)')
Nick Craver
If you want to skip the first and last table rows *and* table cells, `table tr:not(:first-child, :last-child) td:not(:first-child, :last-child)` should work.
Brant Bobby
I think OP wants to exclude the first/last rows as well. :o) EDIT: Can't tell from the question, but perhaps `<th>` cells should be considered too.
patrick dw
@patrick - good call, though I think `<th>` would just be on that first/excluded row, added the row-excluding version
Nick Craver
Yeah, you're probably right about the `<th>`, although I may be inclined to use `:first,:last` for the `<tr>` in case there are multiple table sections. Likely not the case here, but thought I'd note it anyway. :o)
patrick dw
Thanks! I'm not using <th> so this solution works perfectly for me!
MartinStettner
@patrick - I suppose it depends on your case, the downside of `:first` and `:last` is with multiple tables you'd not get what you're after either...I guess it's just a matter of the specific markup this is targeting.
Nick Craver
Nick - Ah, good point. I was only giving consideration to a single table. Hadn't considered multiple.
patrick dw
I suggest `tr>td` to avoid problems with nested tables. Also note this will block the first and last row in each section, not the whole table, when multiple sections (`<tbody>` et al) are in use. If that's not what you want, consider getting the table DOM object and iterating over all but the first and last of `table.rows` and `row.cells`.
bobince
@bobince - That would still find them even nested (since they are direct children of a `<tr>` as well), you would need the full direct-child selector chain to only get the current table.
Nick Craver
Yeah, though the current particular example doesn't specify a particular table so it kind of doesn't make any difference there. The full child selector chain is a good idea, but then you have to include `tbody`, and, if using XHTML, actually include the `<tbody>` in the markup (since HTML and XHTML differ on whether missing tbodies are implied). This sort of thing is why I like the DOM version ;-)
bobince