Method: Nokogiri::XML::Searchable#css
- Defined in:
- lib/nokogiri/xml/searchable.rb
#css(*args) ⇒ Object
call-seq:
css(*rules, [namespace-bindings, custom-pseudo-class])
Search this object for CSS rules
. rules
must be one or more CSS selectors. For example:
node.css('title')
node.css('body h1.bold')
node.css('div + p.green', 'div#one')
A hash of namespace bindings may be appended. For example:
node.css('bike|tire', {'bike' => 'http://schwinn.com/'})
💡 Custom CSS pseudo classes may also be defined which are mapped to a custom XPath function. To define custom pseudo classes, create a class and implement the custom pseudo class you want defined. The first argument to the method will be the matching context NodeSet. Any other arguments are ones that you pass in. For example:
handler = Class.new {
def regex(node_set, regex)
node_set.find_all { |node| node['some_attribute'] =~ /#{regex}/ }
end
}.new
node.css('title:regex("\w+")', handler)
💡 Some XPath syntax is supported in CSS queries. For example, to query for an attribute:
node.css('img > @href') # returns all +href+ attributes on an +img+ element
node.css('img / @href') # same
# ⚠ this returns +class+ attributes from all +div+ elements AND THEIR CHILDREN!
node.css('div @class')
node.css
💡 Array-like syntax is supported in CSS queries as an alternative to using :nth-child().
⚠ NOTE that indices are 1-based like :nth-child
and not 0-based like Ruby Arrays. For example:
# equivalent to 'li:nth-child(2)'
node.css('li[2]') # retrieve the second li element in a list
⚠ NOTE that the CSS query string is case-sensitive with regards to your document type. HTML tags will match only lowercase CSS queries, so if you search for “H1” in an HTML document, you’ll never find anything. However, “H1” might be found in an XML document, where tags names are case-sensitive (e.g., “H1” is distinct from “h1”).
129 130 131 132 133 |
# File 'lib/nokogiri/xml/searchable.rb', line 129 def css(*args) rules, handler, ns, _ = extract_params(args) css_internal(self, rules, handler, ns) end |