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.

221 lines
9.6 KiB

4 years 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.org/fb55/css-select.svg?branch=master)](http://travis-ci.org/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/engine
  3. ## What?
  4. css-select turns CSS selectors into functions that tests if elements match them. When searching for elements, testing is executed "from the top", similar to how browsers execute CSS selectors.
  5. In its default configuration, css-select queries the DOM structure of the [`domhandler`](https://github.com/fb55/domhandler) module (also known as htmlparser2 DOM).
  6. It uses [`domutils`](https://github.com/fb55/domutils) as its default adapter over the DOM structure. See Options below for details on querying alternative DOM structures.
  7. __Features:__
  8. - Full implementation of CSS3 selectors
  9. - Partial implementation of jQuery/Sizzle extensions
  10. - Very high test coverage
  11. - Pretty good performance
  12. ## Why?
  13. The traditional approach of executing CSS selectors, named left-to-right execution, is to execute every component of the selector in order, from left to right _(duh)_. The execution of the selector `a b` for example will first query for `a` elements, then search these for `b` elements. (That's the approach of eg. [`Sizzle`](https://github.com/jquery/sizzle), [`nwmatcher`](https://github.com/dperini/nwmatcher/) and [`qwery`](https://github.com/ded/qwery).)
  14. While this works, it has some downsides: Children of `a`s will be checked multiple times; first, to check if they are also `a`s, then, for every superior `a` once, if they are `b`s. Using [Big O notation](http://en.wikipedia.org/wiki/Big_O_notation), that would be `O(n^(k+1))`, where `k` is the number of descendant selectors (that's the space in the example above).
  15. The far more efficient approach is to first look for `b` elements, then check if they have superior `a` elements: Using big O notation again, that would be `O(n)`. That's called right-to-left execution.
  16. And that's what css-select does – and why it's quite performant.
  17. ## How does it work?
  18. By building a stack of functions.
  19. _Wait, what?_
  20. Okay, so let's suppose we want to compile the selector `a b` again, for right-to-left execution. We start by _parsing_ the selector, which means we turn the selector into an array of the building-blocks of the selector, so we can distinguish them easily. That's what the [`css-what`](https://github.com/fb55/css-what) module is for, if you want to have a look.
  21. Anyway, after parsing, we end up with an array like this one:
  22. ```js
  23. [
  24. { type: 'tag', name: 'a' },
  25. { type: 'descendant' },
  26. { type: 'tag', name: 'b' }
  27. ]
  28. ```
  29. Actually, this array is wrapped in another array, but that's another story (involving commas in selectors).
  30. Now that we know the meaning of every part of the selector, we can compile it. That's where it becomes interesting.
  31. The basic idea is to turn every part of the selector into a function, which takes an element as its only argument. The function checks whether a passed element matches its part of the selector: If it does, the element is passed to the next turned-into-a-function part of the selector, which does the same. If an element is accepted by all parts of the selector, it _matches_ the selector and double rainbow ALL THE WAY.
  32. As said before, we want to do right-to-left execution with all the big O improvements nonsense, so elements are passed from the rightmost part of the selector (`b` in our example) to the leftmost (~~which would be `c`~~ of course `a`).
  33. _//TODO: More in-depth description. Implementation details. Build a spaceship._
  34. ## API
  35. ```js
  36. const CSSselect = require("css-select");
  37. ```
  38. __Note:__ css-select throws errors when invalid selectors are passed to it, contrary to the behavior in browsers, which swallow them. This is done to aid with writing css selectors, but can be unexpected when processing arbitrary strings.
  39. #### `CSSselect(query, elems, options)`
  40. Queries `elems`, returns an array containing all matches.
  41. - `query` can be either a CSS selector or a function.
  42. - `elems` can be either an array of elements, or a single element. If it is an element, its children will be queried.
  43. - `options` is described below.
  44. Aliases: `CSSselect.selectAll(query, elems)`, `CSSselect.iterate(query, elems)`.
  45. #### `CSSselect.compile(query)`
  46. Compiles the query, returns a function.
  47. #### `CSSselect.is(elem, query, options)`
  48. Tests whether or not an element is matched by `query`. `query` can be either a CSS selector or a function.
  49. #### `CSSselect.selectOne(query, elems, options)`
  50. Arguments are the same as for `CSSselect(query, elems)`. Only returns the first match, or `null` if there was no match.
  51. ### Options
  52. - `xmlMode`: When enabled, tag names will be case-sensitive. Default: `false`.
  53. - `strict`: Limits the module to only use CSS3 selectors. Default: `false`.
  54. - `rootFunc`: The last function in the stack, will be called with the last element that's looked at. Should return `true`.
  55. - `adapter`: The adapter to use when interacting with the backing DOM structure. By default it uses [`domutils`](https://github.com/fb55/domutils).
  56. #### Custom Adapters
  57. A custom adapter must implement the following functions:
  58. ```
  59. isTag, existsOne, getAttributeValue, getChildren, getName, getParent,
  60. getSiblings, getText, hasAttrib, removeSubsets, findAll, findOne
  61. ```
  62. The method signature notation used below should be fairly intuitive - if not,
  63. see the [`rtype`](https://github.com/ericelliott/rtype) or
  64. [`TypeScript`](https://www.typescriptlang.org/) docs, as it is very similar to
  65. both of those. You may also want to look at
  66. -[`domutils`](https://github.com/fb55/domutils) to see the default
  67. -implementation, or at
  68. -[`css-select-browser-adapter`](https://github.com/nrkn/css-select-browser-adapter/blob/master/index.js)
  69. -for an implementation backed by the DOM.
  70. ```ts
  71. {
  72. // is the node a tag?
  73. isTag: ( node:Node ) => isTag:Boolean,
  74. // does at least one of passed element nodes pass the test predicate?
  75. existsOne: ( test:Predicate, elems:[ElementNode] ) => existsOne:Boolean,
  76. // get the attribute value
  77. getAttributeValue: ( elem:ElementNode, name:String ) => value:String,
  78. // get the node's children
  79. getChildren: ( node:Node ) => children:[Node],
  80. // get the name of the tag
  81. getName: ( elem:ElementNode ) => tagName:String,
  82. // get the parent of the node
  83. getParent: ( node:Node ) => parentNode:Node,
  84. /*
  85. get the siblings of the node. Note that unlike jQuery's `siblings` method,
  86. this is expected to include the current node as well
  87. */
  88. getSiblings: ( node:Node ) => siblings:[Node],
  89. // get the text content of the node, and its children if it has any
  90. getText: ( node:Node ) => text:String,
  91. // does the element have the named attribute?
  92. hasAttrib: ( elem:ElementNode, name:String ) => hasAttrib:Boolean,
  93. // takes an array of nodes, and removes any duplicates, as well as any nodes
  94. // whose ancestors are also in the array
  95. removeSubsets: ( nodes:[Node] ) => unique:[Node],
  96. // finds all of the element nodes in the array that match the test predicate,
  97. // as well as any of their children that match it
  98. findAll: ( test:Predicate, nodes:[Node] ) => elems:[ElementNode],
  99. // finds the first node in the array that matches the test predicate, or one
  100. // of its children
  101. findOne: ( test:Predicate, elems:[ElementNode] ) => findOne:ElementNode,
  102. /*
  103. The adapter can also optionally include an equals method, if your DOM
  104. structure needs a custom equality test to compare two objects which refer
  105. to the same underlying node. If not provided, `css-select` will fall back to
  106. `a === b`.
  107. */
  108. equals: ( a:Node, b:Node ) => Boolean
  109. }
  110. ```
  111. ## Supported selectors
  112. _As defined by CSS 4 and / or jQuery._
  113. * Universal (`*`)
  114. * Tag (`<tagname>`)
  115. * Descendant (` `)
  116. * Child (`>`)
  117. * Parent (`<`) *
  118. * Sibling (`+`)
  119. * Adjacent (`~`)
  120. * Attribute (`[attr=foo]`), with supported comparisons:
  121. * `[attr]` (existential)
  122. * `=`
  123. * `~=`
  124. * `|=`
  125. * `*=`
  126. * `^=`
  127. * `$=`
  128. * `!=` *
  129. * Also, `i` can be added after the comparison to make the comparison case-insensitive (eg. `[attr=foo i]`) *
  130. * Pseudos:
  131. * `:not`
  132. * `:contains` *
  133. * `:icontains` * (case-insensitive version of `:contains`)
  134. * `:has` *
  135. * `:root`
  136. * `:empty`
  137. * `:parent` *
  138. * `:[first|last]-child[-of-type]`
  139. * `:only-of-type`, `:only-child`
  140. * `:nth-[last-]child[-of-type]`
  141. * `:link`
  142. * `:visited`, `:hover`, `:active` * (these depend on optional Adapter methods, so these will work only if implemented in Adapter)
  143. * `:selected` *, `:checked`
  144. * `:enabled`, `:disabled`
  145. * `:required`, `:optional`
  146. * `:header`, `:button`, `:input`, `:text`, `:checkbox`, `:file`, `:password`, `:reset`, `:radio` etc. *
  147. * `:matches` *
  148. __*__: Not part of CSS3
  149. ---
  150. License: BSD-2-Clause
  151. ## Security contact information
  152. To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security).
  153. Tidelift will coordinate the fix and disclosure.
  154. ## `css-select` for enterprise
  155. Available as part of the Tidelift Subscription
  156. The maintainers of `css-select` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-css-select?utm_source=npm-css-select&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)