-1

Note: I'm not looking for a parent of an element. I'm looking for an element that contains other elements within it.

I’m using Rails 4.2.7 and I'm using Nokogiri to parse HTMl documents. I want to find the table in my document whose first row (first tr element) has at least one th element. How do I write a CSS selector for that? Note that I only want to select the table, not the th elements themselves. Here is an example of the table I would hope to select from within the document

<table>
    <tbody>
        <tr>
            <th>Header 1</th>
        </tr>
        <tr>
            <td>Other data</td>
        </tr>
        …
    </tbody>
</table>
the Tin Man
  • 150,910
  • 39
  • 198
  • 279
Dave
  • 17,420
  • 96
  • 300
  • 582
  • Parent selectors do not exist in css3. Here is one of many articles on it. https://www.google.ca/amp/s/css-tricks.com/parent-selectors-in-css/amp/?client=ms-android-rogers-ca. You could try jquery if thats an option kind of like in this answer. Get table find th get parent. http://stackoverflow.com/a/3523794/3366016 – user3366016 Nov 22 '16 at 23:27
  • Please read "[mcve]". We'd like to see what you tried, not just a sample of your input data. – the Tin Man Nov 22 '16 at 23:33
  • Possible duplicate of [Is there a CSS parent selector?](http://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector) – James Donnelly Nov 23 '16 at 09:39
  • Hi, I'm not looking for the parent of an element. I'm looking for an element htat has an element within it. – Dave Nov 23 '16 at 15:55
  • This isn't really a Nokogiri question if you're asking specifically for a CSS selector to find something, it'd be a CSS question and Nokogiri, Ruby and Rails aren't appropriate tags. – the Tin Man Nov 23 '16 at 23:37

1 Answers1

0

You can try to use the Array#select method that filter all the tables where the first tr contains a th element.

For example, suppose you have a Nokogiri object called doc:

require "nokogiri"
require "open-uri"

url = # your url
doc = Nokogiri::HTML.parse(open(url))

tables = doc.css("table").select do |table|
  # consider only the first row of each table
  first_row = table.css("tr").first

  # check if that row's children contains a <th> element
  first_row.children.map(&:name).include?("th")
end
Marc Moy
  • 136
  • 4