Class: HTML::Selector

Class | HTML::Selector
In: | lib/action_controller/vendor/html-scanner/html/selector.rb
Parent: | Object

Selects HTML elements using CSS 2 selectors.

The `Selector` class uses CSS selector expressions to match and select HTML elements.

For example:

      selector = HTML::Selector.new "form.login[action=/login]"

creates a new selector that matches any `form` element with the class `login` and an attribute `action` with the value `/login`.

### Matching Elements

Use the match method to determine if an element matches the selector.

For simple selectors, the method returns an array with that element, or `nil` if the element does not match. For complex selectors (see below) the method returns an array with all matched elements, of `nil` if no match found.

For example:

      if selector.match(element)
        puts "Element is a login form"
      end

### Selecting Elements

Use the select method to select all matching elements starting with one element and going through all children in depth-first order.

This method returns an array of all matching elements, an empty array if no match is found

For example:

      selector = HTML::Selector.new "input[type=text]"
      matches = selector.select(element)
      matches.each do |match|
        puts "Found text field with name #{match.attributes['name']}"
      end

### Expressions

Selectors can match elements using any of the following criteria:

- `name` — Match an element based on its name (tag name). For example, `p` to match a paragraph. You can use `*` to match any element.
- `#id` — Match an element based on its identifier (the `id` attribute). For example, `#page`.
- `.class` — Match an element based on its class name, all class names if more than one specified.
- `[attr]` — Match an element that has the specified attribute.
- `[attr=value]` — Match an element that has the specified attribute and value. (More operators are supported see below)
- `:pseudo-class` — Match an element based on a pseudo class, such as `:nth-child` and `:empty`.
- `:not(expr)` — Match an element that does not match the negation expression.

When using a combination of the above, the element name comes first followed by identifier, class names, attributes, pseudo classes and negation in any order. Do not seprate these parts with spaces! Space separation is used for descendant selectors.

For example:

      selector = HTML::Selector.new "form.login[action=/login]"

The matched element must be of type `form` and have the class `login`. It may have other classes, but the class `login` is required to match. It must also have an attribute called `action` with the value `/login`.

This selector will match the following element:

      <form class="login form" method="post" action="/login">

but will not match the element:

      <form method="post" action="/logout">

### Attribute Values

Several operators are supported for matching attributes:

- `name` — The element must have an attribute with that name.
- `name=value` — The element must have an attribute with that name and value.
- `name^=value` — The attribute value must start with the specified value.
- `name$=value` — The attribute value must end with the specified value.
- `name*=value` — The attribute value must contain the specified value.
- `name~=word` — The attribute value must contain the specified word (space separated).
- `name|=word` — The attribute value must start with specified word.

For example, the following two selectors match the same element:

      #my_id
      [id=my_id]

and so do the following two selectors:

      .my_class
      [class~=my_class]

### Alternatives, siblings, children

Complex selectors use a combination of expressions to match elements:

- `expr1 expr2` — Match any element against the second expression if it has some parent element that matches the first expression.
- `expr1 > expr2` — Match any element against the second expression if it is the child of an element that matches the first expression.
- `expr1 + expr2` — Match any element against the second expression if it immediately follows an element that matches the first expression.
- `expr1 ~ expr2` — Match any element against the second expression that comes after an element that matches the first expression.
- `expr1, expr2` — Match any element against the first expression, or against the second expression.

Since children and sibling selectors may match more than one element given the first element, the match method may return more than one match.

### Pseudo classes

Pseudo classes were introduced in CSS 3. They are most often used to select elements in a given position:

- `:root` — Match the element only if it is the root element (no parent element).
- `:empty` — Match the element only if it has no child elements, and no text content.
- `:only-child` — Match the element if it is the only child (element) of its parent element.
- `:only-of-type` — Match the element if it is the only child (element) of its parent element and its type.
- `:first-child` — Match the element if it is the first child (element) of its parent element.
- `:first-of-type` — Match the element if it is the first child (element) of its parent element of its type.
- `:last-child` — Match the element if it is the last child (element) of its parent element.
- `:last-of-type` — Match the element if it is the last child (element) of its parent element of its type.
- `:nth-child(b)` — Match the element if it is the b-th child (element) of its parent element. The value `b` specifies its index, starting with 1.
- `:nth-child(an+b)` — Match the element if it is the b-th child (element) in each group of `a` child elements of its parent element.
- `:nth-child(-an+b)` — Match the element if it is the first child (element) in each group of `a` child elements, up to the first `b` child elements of its parent element.
- `:nth-child(odd)` — Match element in the odd position (i.e. first, third). Same as `:nth-child(2n+1)`.
- `:nth-child(even)` — Match element in the even position (i.e. second, fourth). Same as `:nth-child(2n+2)`.
- `:nth-of-type(..)` — As above, but only counts elements of its type.
- `:nth-last-child(..)` — As above, but counts from the last child.
- `:nth-last-of-type(..)` — As above, but counts from the last child and only elements of its type.
- `:not(selector)` — Match the element only if the element does not match the simple selector.

As you can see, <tt>:nth-child<tt> pseudo class and its varient can get quite tricky and the CSS specification doesn‘t do a much better job explaining it. But after reading the examples and trying a few combinations, it‘s easy to figure out.

For example:

      table tr:nth-child(odd)

Selects every second row in the table starting with the first one.

      div p:nth-child(4)

Selects the fourth paragraph in the `div`, but not if the `div` contains other elements, since those are also counted.

      div p:nth-of-type(4)

Selects the fourth paragraph in the `div`, counting only paragraphs, and ignoring all other elements.

      div p:nth-of-type(-n+4)

Selects the first four paragraphs, ignoring all others.

And you can always select an element that matches one set of rules but not another using `:not`. For example:

      p:not(.post)

Matches all paragraphs that do not have the class `.post`.

### Substitution Values

You can use substitution with identifiers, class names and element values. A substitution takes the form of a question mark (`?`) and uses the next value in the argument list following the CSS expression.

The substitution value may be a string or a regular expression. All other values are converted to strings.

For example:

      selector = HTML::Selector.new "#?", /^\d+$/

matches any element whose identifier consists of one or more digits.

See www.w3.org/TR/css3-selectors/

### Methods

attribute_match for_class for_id match new next_element next_selector nth_child only_child select select_first simple_selector

### Public Class methods

Selector.for_class(cls) => selector

Creates a new selector for the given class name.

Selector.for_id(id) => selector

Creates a new selector for the given id.

Selector.new(string, [values ...]) => selector

Creates a new selector from a CSS 2 selector expression.

The first argument is the selector expression. All other arguments are used for value substitution.

Throws InvalidSelectorError is the selector expression is invalid.

### Public Instance methods

match(element, first?) => array or nil

Matches an element against the selector.

For a simple selector this method returns an array with the element if the element matches, nil otherwise.

For a complex selector (sibling and descendant) this method returns an array with all matching elements, nil if no match is found.

Use +first_only=true+ if you are only interested in the first element.

For example:

      if selector.match(element)
        puts "Element is a login form"
      end

next_element(element, name = nil)

Return the next element after this one. Skips sibling text nodes.

With the `name` argument, returns the next element with that name, skipping other sibling elements.

select(root) => array

Selects and returns an array with all matching elements, beginning with one node and traversing through all children depth-first. Returns an empty array if no match is found.

The root node may be any element in the document, or the document itself.

For example:

      selector = HTML::Selector.new "input[type=text]"
      matches = selector.select(element)
      matches.each do |match|
        puts "Found text field with name #{match.attributes['name']}"
      end

select_first(root)

Similar to select but returns the first matching element. Returns `nil` if no element matches the selector.

### Protected Instance methods

attribute_match(equality, value)

Create a regular expression to match an attribute value based on the equality operator (=, ^=, |=, etc).

next_selector(statement, values)

Called to create a dependent selector (sibling, descendant, etc). Passes the remainder of the statement that will be reduced to zero eventually, and array of substitution values.

This method is called from four places, so it helps to put it here for reuse. The only logic deals with the need to detect comma separators (alternate) and apply them to the selector group of the top selector.

nth_child(a, b, of_type, reverse)

Returns a lambda that can match an element against the nth-child pseudo class, given the following arguments:

- `a` — Value of a part.
- `b` — Value of b part.
- `of_type` — True to test only elements of this type (of-type).
- `reverse` — True to count in reverse order (last-).

only_child(of_type)

Creates a only child lambda. Pass +of-type+ to only look at elements of its type.

simple_selector(statement, values, can_negate = true)

Creates a simple selector given the statement and array of substitution values.

Returns a hash with the values `tag_name`, `attributes`, `pseudo` (classes) and `negation`.

Called the first time with `can_negate` true to allow negation. Called a second time with false since negation cannot be negated.

[Validate]