views:

44

answers:

4

I'm working with a mess of HTML markup. In order to get reliable matches I have resorted to explicitly querying a chain of elements using the '>' operator.

For this question I am attempting to select the parent of an explicit chain of descendents.

For example, I'd like to select the table element with class 'toolbar' in the following HTML:

<table class='toolbar'>
  <tbody>
    <tr>
      <td class='button'>
        ...
      </td>
    </tr>
  </tbody>
</table>

Here is what I've tried:

1. Use 'has'

$("table.toolbar:has(tbody > tr > td.button)")

Here elements are matched even if tbody isn't a direct descendent of table so this doesn't reliably work.

2. Use '>' and parent()

$("table.toolbar > tbody > tr > td.button").parent().parent().parent()

This works but is messy. Also have to make sure the correct number of parent() calls are included.

3. ???

Due to the crap HTML, it is critical that elements are explicitly given in the query as one direct descendent beneath another.

Can anyone please help with the nicest way of doing this? Thanks!

+1  A: 
$("td.button").parents("table.toolbar")

seems the easiest way.

cletus
I think,The second is correct but the first will select the td elements with calss "button"
Marwan Aouida
Thanks, I haven't seen the parents function before. However this query would be too 'loose' and match too much. I've clarified the first sentence to explain this better.
Alex Angas
A: 

Updated:
you can use:

$("table.toolbar:has(tbody:has(td.button))")
Marwan Aouida
Unfortunately too 'loose' and matches too much. I've clarified the first sentence to explain this better.
Alex Angas
updated, try now
Marwan Aouida
Thank you, but this doesn't match the requirement that td.button is the immediate descendent of tbody, and that tbody is the immediate descendent of table.toolbar. It will match even if there are other tags in-between.
Alex Angas
A: 

I think:

$("td.button").closest("table.toolbar")

tanathos
A: 
$("table.toolbar > tbody > tr > td.button").closest("table.toolbar")

Still a bit messy but should work.

Maiku Mori