PureHTML.Query.Selector.Parser (PureHTML v0.5.0)

View Source

Parses CSS selector tokens into Selector structs.

Summary

Functions

Parses a CSS selector string into a list of selector chains.

Types

combinator()

@type combinator() ::
  nil | :descendant | :child | :adjacent_sibling | :general_sibling

error()

@type error() :: {:invalid_selector, String.t()}

selector_chain()

@type selector_chain() :: [{combinator(), PureHTML.Query.Selector.t()}]

Functions

parse(selector_string)

@spec parse(String.t()) :: {:ok, [selector_chain()]} | {:error, error()}

Parses a CSS selector string into a list of selector chains.

Each chain is a list of {combinator, selector} tuples where combinator indicates the relationship to the previous selector in the chain.

Combinators

  • nil - First selector in chain (no combinator)
  • :descendant - Descendant combinator (space)
  • :child - Child combinator (>)
  • :adjacent_sibling - Adjacent sibling combinator (+)
  • :general_sibling - General sibling combinator (~)

Examples

iex> PureHTML.Query.Selector.Parser.parse("div")
{:ok, [[{nil, %PureHTML.Query.Selector{type: "div"}}]]}

iex> PureHTML.Query.Selector.Parser.parse("div > p")
{:ok, [[{nil, %PureHTML.Query.Selector{type: "div"}}, {:child, %PureHTML.Query.Selector{type: "p"}}]]}

iex> PureHTML.Query.Selector.Parser.parse(".a, .b")
{:ok, [[{nil, %PureHTML.Query.Selector{classes: ["a"]}}], [{nil, %PureHTML.Query.Selector{classes: ["b"]}}]]}

iex> PureHTML.Query.Selector.Parser.parse("div >")
{:error, {:invalid_selector, "expected a compound selector"}}