2016-11-22 103 views
-1

注意:我不在尋找元素的父項。我正在查找包含其中的其他元素的元素。如何爲包含其他元素的元素編寫CSS選擇器?

我正在使用Rails 4.2.7,我正在使用Nokogiri來解析HTMl文檔。我想在我的文檔中找到第一行(第一個tr元素)至少有一個th元素的表格。我該如何編寫一個CSS選擇器?請注意,我只想選擇表格,而不是第th個元素本身。這是我希望從文檔

<table> 
    <tbody> 
     <tr> 
      <th>Header 1</th> 
     </tr> 
     <tr> 
      <td>Other data</td> 
     </tr> 
     … 
    </tbody> 
</table> 
+0

家長選擇不CSS3存在。這是其中的許多文章之一。 https://www.google.ca/amp/s/css-tricks.com/parent-selectors-in-css/amp/?client=ms-android-rogers-ca。你可以嘗試jquery,如果這是一個選擇類似於這個答案。得到表找到父母。 http://stackoverflow.com/a/3523794/3366016 – user3366016

+0

請閱讀「[mcve]」。我們希望看到您嘗試的是什麼,而不僅僅是您的輸入數據樣本。 –

+0

可能重複的[是否有一個CSS父母選擇器?](http://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector) –

回答

0

你可以嘗試使用Array#select方法過濾器中的所有表,其中第一tr包含th元素中選擇該表的一個例子。

例如,假設你有一個Nokogiri對象調用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 
相關問題