Module: CSS::Selectors::Matcher

Extended by:
Matcher
Included in:
Matcher
Defined in:
lib/css/selectors/matcher.rb

Overview

Matches a Selector AST against any duck-typed element. Required methods on the element:

- `name` (or `tag_name`)            — tag name
- `[](attr)`                         — attribute value or nil
- `parent`                           — parent element or non-element
- `previous_element` (or `previous_element_sibling`) — preceding
  element sibling
- `next_element` (or `next_element_sibling`)         — following
  element sibling
- `children` (and optionally `element_children`) — child nodes

‘Nokogiri::XML::Element` and `Nokogiri::HTML::Element` satisfy this protocol out of the box.

Pseudo-classes that depend on user-agent state (‘:hover`, `:focus`, `:visited`, validity-API states, `:fullscreen`, etc.) always return false; this matcher is intended for stateless analysis.

Defined Under Namespace

Classes: Context

Constant Summary collapse

DISABLEABLE_TAGS =
%w[button input select textarea optgroup option fieldset].freeze
INPUT_TAGS =
%w[input textarea select].freeze
%w[a area link].freeze
RO_INPUT_TYPES =
%w[hidden range color checkbox radio file submit image reset button].freeze
EMPTY_CLASS_SET =
Set.new.freeze

Instance Method Summary collapse

Instance Method Details

#classes_of(element, cache = nil) ⇒ Object



123
124
125
126
# File 'lib/css/selectors/matcher.rb', line 123

def classes_of(element, cache = nil)
  ctx = context_for(element, cache)
  ctx ? ctx.classes : build_class_set(element)
end

#id_of(element, cache = nil) ⇒ Object



118
119
120
121
# File 'lib/css/selectors/matcher.rb', line 118

def id_of(element, cache = nil)
  ctx = context_for(element, cache)
  ctx ? ctx.id : attr(element, 'id')
end

#matches?(element, selector, cache: nil) ⇒ Boolean

Returns:

  • (Boolean)


37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/css/selectors/matcher.rb', line 37

def matches?(element, selector, cache: nil)
  sel = selector.is_a?(String) ? Parser.parse_selector_list(selector) : selector

  case sel
  when SelectorList
    sel.selectors.any? { match_complex(element, it, cache) }
  when ComplexSelector
    match_complex(element, sel, cache)
  when CompoundSelector
    match_compound(element, sel, cache)
  else
    raise ArgumentError, "expected a selector node or string, got #{sel.class}"
  end
end

#tag_of(element, cache = nil) ⇒ Object



113
114
115
116
# File 'lib/css/selectors/matcher.rb', line 113

def tag_of(element, cache = nil)
  ctx = context_for(element, cache)
  ctx ? ctx.tag : tag(element)
end