I’m looking for the pseudoclass :has in Nokogiri.
It should work just like jQuery’s has selector.
For example:
<li><h1><a href="dfd">ex1</a></h1><span class="string">sdfsdf</span></li>
<li><h1><a href="dsfsdf">ex2</a></h1><span class="string"></span></li>
<li><h1><a href="sdfd">ex3</a></h1></li>
The CSS selector should return only the first link, the one with the not-empty span.string sibling.
In jQuery this selector works well:
$('li:has(span.string:not(:empty))>h1>a')
but not in Nokogiri:
Nokogiri::HTML(html_source).css('li:has(span.string:not(:empty))>h1>a')
:not and :empty works well, but not :has.
- Is there any documentation for CSS selectors in Nokogiri?
- Maybe someone can write a custom
:haspseudo class? Here is an example how to write a:regexpselector. - Optionally I can use XPath. How do I write XPath for
li:has(span.string:not(:empty))>h1>a?
The problem with Nokogiri’s current implementation of
:has()is that it creates XPath that requires the contents to be a direct child, not any descendant:To make this XPath match what jQuery does, you need to allow the
spanto be a descendant element. For example:For your specific case, here’s the full “broken” XPath:
And here it is fixed: