whizcreed
whizcreed

Reputation: 2762

How do I select the parent of a specific type of element?

<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

Answers (4)

Borodin
Borodin

Reputation: 126722

XPath makes this a lot easier

tbody = page.xpath '//tbody[tr/td[contains(.,"HP")]]'

Upvotes: 2

pguardiario
pguardiario

Reputation: 54984

I'm going with:

page.at('td[text()*="HP"]').ancestors('tbody')[0]

Upvotes: 3

reto
reto

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

Ju Liu
Ju Liu

Reputation: 3999

Something like this should work

page.search('td').text_includes('HP').xpath('./ancestor::tbody[1]')

Upvotes: 0

Related Questions