I'm using Ruby 2.4 and Nokogiri. I have this for finding an element on my page with certain text ...
a_elt = doc.at('a:contains("MY TEXT")')
How can I make the :contains case insenstiive? I'm not guaranteed the text will always be upper case.
With CSS selector rules this should not be possible as far as I know. But XPath 2.0 would able to check for text case insensitive either by transforming the text content with upper-case()
or using matches()
with third parameter 'i'
instead of contains()
, which will match with a case insensitive regular expression. Nokogiri internally transforms CSS selectors into an XPath query, so your example becomes //a[contains(., "MY TEXT")
. However, Nokogiri's XML features are based on libxml2
(MRI Ruby) or javax.xml.xpath
(JRuby) which do not support Xpath 2.0.
If this was supported you could just replace the CSS selector with this XPath query:
//a[contains(upper-case(.), "MY TEXT")]
But you can just implement the text comparison directly in ruby like this:
a_elt = doc.xpath('//a').detect { |node| /MY TEXT/i === node.text }