How to select nodes by matching text

Zando picture Zando · Sep 25, 2009 · Viewed 31.2k times · Source

If I have a bunch of elements like:

<p>A paragraph <ul><li>Item 1</li><li>Apple</li><li>Orange</li></ul></p>

Is there a built-in method in Nokogiri that would get me all p elements that contain the text "Apple"? (The example element above would match, for instance).

Answer

the Tin Man picture the Tin Man · Mar 10, 2013

Nokogiri can do this (now) using jQuery extensions to CSS:

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"