Mike Mike - 4 months ago 30
Ruby Question

How to check if one of the options in my select menu contains text?

I’m using Rails 4.2.7 with Nokogiri. Is there a way I can tell, with Nokogiri, that one of the options in my select menu contains the word "Results" in its text field (that would be visible to the end user)?

I have:

options = doc.css("#menu_id option")

And I can cycle through all of them, checking the text, but I figured there might be a CSS-selector expression or something similar I can do with Nokogiri that would tell me this answer more quickly.


Nokogiri supports jQuery's :contains selector, which selects nodes with the given content:

doc.css(“#menu_id option:contains('Results'")

You could also do it with an XPath, which has more power but is more verbose:

doc.xpath('//*[@id='menu_id']//option[contains(text(), "Results")]')

See "Nokogiri: How to select nodes by matching text?".