I got the name of a CSS class from a Nokogiri node. Now I want to find all the nodes that also have the same class attached.
I don't know which HTML tag the element that I'm looking for has, and how deep it is. All i know is what class to search for.
I have already tried:
doc.xpath("//*[contains(@class, #{css})]")
But this seems to return WAY too many elements.
Also I have tried:
doc.xpath("//*[@class, #{css}]")
and this returns nothing.
I want to get the elements that contain that class, not every element that surrounds an element with that class.
Is it possible to do this with Nokogiri?
Assuming that the class name is stored into
class_name
, I think thatis what you're looking for.
This will match all the elements that contain
class_name
into their classes, ie ifclass_name
is 'box', then it will match both elements likediv class="box"
and elements likediv class="box left"
If you only want to match elements like
div class="box"
ie that have only one class and that class is the one you're looking for, then you could use this: