Reputation: 2762
<table>
<tbody>
<tr>
<td>
Product Name
</td>
</tr>
<tr>
<td>
Apple
</td>
</tr>
<tr>
<td>
Dell
</td>
</tr>
<tr>
<td>
HP
</td>
</tr>
</tbody>
</table>
From the above HTML code I should be able to do something like:
page.search('td').text_includes('HP').last.up('tbody')
I can do this by calling parent
several times on that <td>
, but I want to traverse up until I find <tbody>
and get that element. jQuery has this ability, but I am not sure how to do this with Nokogiri.
Upvotes: 2
Views: 127
Reputation: 126722
XPath makes this a lot easier
tbody = page.xpath '//tbody[tr/td[contains(.,"HP")]]'
Upvotes: 2
Reputation: 54984
I'm going with:
page.at('td[text()*="HP"]').ancestors('tbody')[0]
Upvotes: 3
Reputation: 16732
See Nokogiri equivalent of jQuery closest() method for finding first matching ancestor in tree
so for example:
src = (element.ancestors('table').first || { })['src']
or in rails:
src = element.ancestors('table').first.try(:fetch, 'src')
Upvotes: 0
Reputation: 3999
Something like this should work
page.search('td').text_includes('HP').xpath('./ancestor::tbody[1]')
Upvotes: 0