LoginSignup
1
3

More than 5 years have passed since last update.

特定の子要素を持つ要素をCSSセレクタで選択したい

Posted at

NokogiriのCSSセレクタは各ブラウザで実装されてるのよりも高機能らしくhasが使えます。

例えば

foo.html
<table>
  <tr><th>HEAD</th></tr>
  <tr><td>BODY</td></tr>
</table>

みたいな構造のとき、ヘッダー以外のテーブルデータ部分が欲しくて

doc = Nokogiri::HTML(url.read)
doc.css('table tr')[1..-1]

なんて書き方をしてたんですが、

doc = Nokogiri::HTML(url.read)
doc.css('table tr:has(td)')

のように何をしてるか明示的に書けるんです。素敵!

おまけ

Selectors Level 4 で提案されてるので将来的にはブラウザでも使えるようなるみたいですね。

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3