You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

255 lines
12 KiB

3 months ago
  1. # css-select [![NPM version](http://img.shields.io/npm/v/css-select.svg)](https://npmjs.org/package/css-select) [![Build Status](https://travis-ci.com/fb55/css-select.svg?branch=master)](http://travis-ci.com/fb55/css-select) [![Downloads](https://img.shields.io/npm/dm/css-select.svg)](https://npmjs.org/package/css-select) [![Coverage](https://coveralls.io/repos/fb55/css-select/badge.svg?branch=master)](https://coveralls.io/r/fb55/css-select)
  2. A CSS selector compiler and engine
  3. ## What?
  4. As a **compiler**, css-select turns CSS selectors into functions that tests if
  5. elements match them.
  6. As an **engine**, css-select looks through a DOM tree, searching for elements.
  7. Elements are tested "from the top", similar to how browsers execute CSS
  8. selectors.
  9. In its default configuration, css-select queries the DOM structure of the
  10. [`domhandler`](https://github.com/fb55/domhandler) module (also known as
  11. htmlparser2 DOM). To query alternative DOM structures, see [`Options`](#options)
  12. below.
  13. **Features:**
  14. - 🔬 Full implementation of CSS3 selectors, as well as most CSS4 selectors
  15. - 🧪 Partial implementation of jQuery/Sizzle extensions (see
  16. [cheerio-select](https://github.com/cheeriojs/cheerio-select) for the
  17. remaining selectors)
  18. - 🧑‍🔬 High test coverage, including the full test suites from Sizzle, Qwery and
  19. NWMatcher.
  20. - 🥼 Reliably great performance
  21. ## Why?
  22. Most CSS engines written in JavaScript execute selectors left-to-right. That
  23. means thet execute every component of the selector in order, from left to right
  24. _(duh)_. As an example: For the selector `a b`, these engines will first query
  25. for `a` elements, then search these for `b` elements. (That's the approach of
  26. eg. [`Sizzle`](https://github.com/jquery/sizzle),
  27. [`nwmatcher`](https://github.com/dperini/nwmatcher/) and
  28. [`qwery`](https://github.com/ded/qwery).)
  29. While this works, it has some downsides: Children of `a`s will be checked
  30. multiple times; first, to check if they are also `a`s, then, for every superior
  31. `a` once, if they are `b`s. Using
  32. [Big O notation](http://en.wikipedia.org/wiki/Big_O_notation), that would be
  33. `O(n^(k+1))`, where `k` is the number of descendant selectors (that's the space
  34. in the example above).
  35. The far more efficient approach is to first look for `b` elements, then check if
  36. they have superior `a` elements: Using big O notation again, that would be
  37. `O(n)`. That's called right-to-left execution.
  38. And that's what css-select does – and why it's quite performant.
  39. ## How does it work?
  40. By building a stack of functions.
  41. _Wait, what?_
  42. Okay, so let's suppose we want to compile the selector `a b`, for right-to-left
  43. execution. We start by _parsing_ the selector. This turns the selector into an
  44. array of the building blocks. That's what the
  45. [`css-what`](https://github.com/fb55/css-what) module is for, if you want to
  46. have a look.
  47. Anyway, after parsing, we end up with an array like this one:
  48. ```js
  49. [
  50. { type: "tag", name: "a" },
  51. { type: "descendant" },
  52. { type: "tag", name: "b" },
  53. ];
  54. ```
  55. (Actually, this array is wrapped in another array, but that's another story,
  56. involving commas in selectors.)
  57. Now that we know the meaning of every part of the selector, we can compile it.
  58. That is where things become interesting.
  59. The basic idea is to turn every part of the selector into a function, which
  60. takes an element as its only argument. The function checks whether a passed
  61. element matches its part of the selector: If it does, the element is passed to
  62. the next function representing the next part of the selector. That function does
  63. the same. If an element is accepted by all parts of the selector, it _matches_
  64. the selector and double rainbow ALL THE WAY.
  65. As said before, we want to do right-to-left execution with all the big O
  66. improvements. That means elements are passed from the rightmost part of the
  67. selector (`b` in our example) to the leftmost (~~which would be `c`~~ of course
  68. `a`).
  69. For traversals, such as the _descendant_ operating the space between `a` and
  70. `b`, we walk up the DOM tree, starting from the element passed as argument.
  71. _//TODO: More in-depth description. Implementation details. Build a spaceship._
  72. ## API
  73. ```js
  74. const CSSselect = require("css-select");
  75. ```
  76. **Note:** css-select throws errors when invalid selectors are passed to it.This
  77. is done to aid with writing css selectors, but can be unexpected when processing
  78. arbitrary strings.
  79. #### `CSSselect.selectAll(query, elems, options)`
  80. Queries `elems`, returns an array containing all matches.
  81. - `query` can be either a CSS selector or a function.
  82. - `elems` can be either an array of elements, or a single element. If it is an
  83. element, its children will be queried.
  84. - `options` is described below.
  85. Aliases: `default` export, `CSSselect.iterate(query, elems)`.
  86. #### `CSSselect.compile(query, options)`
  87. Compiles the query, returns a function.
  88. #### `CSSselect.is(elem, query, options)`
  89. Tests whether or not an element is matched by `query`. `query` can be either a
  90. CSS selector or a function.
  91. #### `CSSselect.selectOne(query, elems, options)`
  92. Arguments are the same as for `CSSselect.selectAll(query, elems)`. Only returns
  93. the first match, or `null` if there was no match.
  94. ### Options
  95. All options are optional.
  96. - `xmlMode`: When enabled, tag names will be case-sensitive. Default: `false`.
  97. - `rootFunc`: The last function in the stack, will be called with the last
  98. element that's looked at.
  99. - `adapter`: The adapter to use when interacting with the backing DOM
  100. structure. By default it uses the `domutils` module.
  101. - `context`: The context of the current query. Used to limit the scope of
  102. searches. Can be matched directly using the `:scope` pseudo-selector.
  103. - `cacheResults`: Allow css-select to cache results for some selectors,
  104. sometimes greatly improving querying performance. Disable this if your
  105. document can change in between queries with the same compiled selector.
  106. Default: `true`.
  107. #### Custom Adapters
  108. A custom adapter must match the interface described
  109. [here](https://github.com/fb55/css-select/blob/1aa44bdd64aaf2ebdfd7f338e2e76bed36521957/src/types.ts#L6-L96).
  110. You may want to have a look at [`domutils`](https://github.com/fb55/domutils) to
  111. see the default implementation, or at
  112. [`css-select-browser-adapter`](https://github.com/nrkn/css-select-browser-adapter/blob/master/index.js)
  113. for an implementation backed by the DOM.
  114. ## Supported selectors
  115. _As defined by CSS 4 and / or jQuery._
  116. - [Selector lists](https://developer.mozilla.org/en-US/docs/Web/CSS/Selector_list)
  117. (`,`)
  118. - [Universal](https://developer.mozilla.org/en-US/docs/Web/CSS/Universal_selectors)
  119. (`*`)
  120. - [Type](https://developer.mozilla.org/en-US/docs/Web/CSS/Type_selectors)
  121. (`<tagname>`)
  122. - [Descendant](https://developer.mozilla.org/en-US/docs/Web/CSS/Descendant_combinator)
  123. (` `)
  124. - [Child](https://developer.mozilla.org/en-US/docs/Web/CSS/Child_combinator)
  125. (`>`)
  126. - Parent (`<`)
  127. - [Adjacent sibling](https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_combinator)
  128. (`+`)
  129. - [General sibling](https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_combinator)
  130. (`~`)
  131. - [Attribute](https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors)
  132. (`[attr=foo]`), with supported comparisons:
  133. - `[attr]` (existential)
  134. - `=`
  135. - `~=`
  136. - `|=`
  137. - `*=`
  138. - `^=`
  139. - `$=`
  140. - `!=`
  141. - `i` and `s` can be added after the comparison to make the comparison
  142. case-insensitive or case-sensitive (eg. `[attr=foo i]`). If neither is
  143. supplied, css-select will follow the HTML spec's
  144. [case-sensitivity rules](https://html.spec.whatwg.org/multipage/semantics-other.html#case-sensitivity-of-selectors).
  145. - Pseudos:
  146. - [`:not`](https://developer.mozilla.org/en-US/docs/Web/CSS/:not)
  147. - [`:contains`](https://api.jquery.com/contains-selector)
  148. - `:icontains` (case-insensitive version of `:contains`)
  149. - [`:has`](https://developer.mozilla.org/en-US/docs/Web/CSS/:has)
  150. - [`:root`](https://developer.mozilla.org/en-US/docs/Web/CSS/:root)
  151. - [`:empty`](https://developer.mozilla.org/en-US/docs/Web/CSS/:empty)
  152. - [`:parent`](https://api.jquery.com/parent-selector)
  153. - [`:first-child`](https://developer.mozilla.org/en-US/docs/Web/CSS/:first-child),
  154. [`:last-child`](https://developer.mozilla.org/en-US/docs/Web/CSS/:last-child),
  155. [`:first-of-type`](https://developer.mozilla.org/en-US/docs/Web/CSS/:first-of-type),
  156. [`:last-of-type`](https://developer.mozilla.org/en-US/docs/Web/CSS/:last-of-type)
  157. - [`:only-of-type`](https://developer.mozilla.org/en-US/docs/Web/CSS/:only-of-type),
  158. [`:only-child`](https://developer.mozilla.org/en-US/docs/Web/CSS/:only-child)
  159. - [`:nth-child`](https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child),
  160. [`:nth-last-child`](https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-child),
  161. [`:nth-of-type`](https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-of-type),
  162. [`:nth-last-of-type`](https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-of-type),
  163. - [`:link`](https://developer.mozilla.org/en-US/docs/Web/CSS/:link),
  164. [`:any-link`](https://developer.mozilla.org/en-US/docs/Web/CSS/:any-link)
  165. - [`:visited`](https://developer.mozilla.org/en-US/docs/Web/CSS/:visited),
  166. [`:hover`](https://developer.mozilla.org/en-US/docs/Web/CSS/:hover),
  167. [`:active`](https://developer.mozilla.org/en-US/docs/Web/CSS/:active)
  168. (these depend on optional `Adapter` methods, so these will only match
  169. elements if implemented in `Adapter`)
  170. - [`:selected`](https://api.jquery.com/selected-selector),
  171. [`:checked`](https://developer.mozilla.org/en-US/docs/Web/CSS/:checked)
  172. - [`:enabled`](https://developer.mozilla.org/en-US/docs/Web/CSS/:enabled),
  173. [`:disabled`](https://developer.mozilla.org/en-US/docs/Web/CSS/:disabled)
  174. - [`:required`](https://developer.mozilla.org/en-US/docs/Web/CSS/:required),
  175. [`:optional`](https://developer.mozilla.org/en-US/docs/Web/CSS/:optional)
  176. - [`:header`](https://api.jquery.com/header-selector),
  177. [`:button`](https://api.jquery.com/button-selector),
  178. [`:input`](https://api.jquery.com/input-selector),
  179. [`:text`](https://api.jquery.com/text-selector),
  180. [`:checkbox`](https://api.jquery.com/checkbox-selector),
  181. [`:file`](https://api.jquery.com/file-selector),
  182. [`:password`](https://api.jquery.com/password-selector),
  183. [`:reset`](https://api.jquery.com/reset-selector),
  184. [`:radio`](https://api.jquery.com/radio-selector) etc.
  185. - [`:is`](https://developer.mozilla.org/en-US/docs/Web/CSS/:is), plus its
  186. legacy alias `:matches`
  187. - [`:scope`](https://developer.mozilla.org/en-US/docs/Web/CSS/:scope)
  188. (uses the context from the passed options)
  189. ---
  190. License: BSD-2-Clause
  191. ## Security contact information
  192. To report a security vulnerability, please use the
  193. [Tidelift security contact](https://tidelift.com/security). Tidelift will
  194. coordinate the fix and disclosure.
  195. ## `css-select` for enterprise
  196. Available as part of the Tidelift Subscription
  197. The maintainers of `css-select` and thousands of other packages are working with
  198. Tidelift to deliver commercial support and maintenance for the open source
  199. dependencies you use to build your applications. Save time, reduce risk, and
  200. improve code health, while paying the maintainers of the exact dependencies you
  201. use.
  202. [Learn more.](https://tidelift.com/subscription/pkg/npm-css-select?utm_source=npm-css-select&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)