8

"Nokogiri: How to select nodes by matching text?" can do this via XPath, however, I am looking for a way to use a CSS select that matches the text of element.

PyQuery and PHPQuery can do this. Isn't there a jQuery API lib for Ruby?

Community
  • 1
  • 1
h34y
  • 489
  • 1
  • 6
  • 11

2 Answers2

15

Nokogiri (now) implements jQuery selectors, making it possible to search the text of a node:

For instance:

require 'nokogiri'

html = '
<html>
  <body>
    <p>foo</p>
    <p>bar</p>
  </body>
</html>
'

doc = Nokogiri::HTML(html)
doc.at('p:contains("bar")').text.strip
=> "bar"
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
3

Cannot be done with pure CSS, you'll have to mix it with Ruby code

  doc = Nokogiri::HTML("<p>A paragraph <ul><li>Item 1</li><li>Apple</li><li>Orange</li></ul></p>")
  p doc.css('li').select{|li|li.text =~ /Apple/}
akuhn
  • 27,477
  • 2
  • 76
  • 91