Selectors decision tree - pick matching selectors, fast.
The problem statement: there are multiple CSS selectors with attached handlers, and a HTML DOM to process. For each HTML Element a matching handler has to be found and applied.
The naive approach is to walk through the DOM and test each and every selector against each Element. This means O(n*m) complexity.
It is pretty clear though that if we have selectors that share something in common then we can reduce the number of checks.
The main selderee
package offers the selectors tree structure. Runnable decision functions for specific DOM implementations are built via plugins.
~
), descendants (
) and same column combinators (||
) are also not supported.selderee
vs css-select
css-select - a CSS selector compiler & engine.
| Feature | selderee
| css-select
|
| ------------------------------------- | :--------: | :----------: |
| Support for htmlparser2
DOM AST | plugin | + |
| "Compiles" into a function | + | + |
| Pick selector(s) for a given Element | + | |
| Query Element(s) for a given selector | | + |
| Package | Version | Folder | Changelog |
| --------- | --------- | --------- | --------- |
| selderee | | /packages/selderee | changelog |
| @selderee/plugin-htmlparser2 |
| /packages/plugin-htmlparser2 | changelog |
```shell
npm i selderee @selderee/plugin-htmlparser2 ```
```js const htmlparser2 = require('htmlparser2'); const util = require('util');
const { DecisionTree, Treeify } = require('selderee'); const { hp2Builder } = require('@selderee/plugin-htmlparser2');
const selectorValuePairs = [ ['p', 'A'], ['p.foo[bar]', 'B'], ['p[class~=foo]', 'C'], ['div.foo', 'D'], ['div > p.foo', 'E'], ['div > p', 'F'], ['#baz', 'G'] ];
// Make a tree structure from all given selectors. const selectorsDecisionTree = new DecisionTree(selectorValuePairs);
// treeify
builder produces a string output for testing and debug purposes.
// treeify
expects string values attached to each selector.
const prettyTree = selectorsDecisionTree.build(Treeify.treeify);
console.log(prettyTree);
const html = /html/`
second
`; const dom = htmlparser2.parseDocument(html); const element = dom.children[0].children[0].children[1].children[0];
// hp2Builder
produces a picker that can pick values
// from the selectors tree.
const picker = selectorsDecisionTree.build(hp2Builder);
// Get all matches const allMatches = picker.pickAll(element); console.log(util.inspect(allMatches, { breakLength: 70, depth: null }));
// or get the value from the most specific match.
const bestMatch = picker.pick1(element);
console.log(Best matched value: ${bestMatch}
);
```
Targeting Node.js version >=14.
Monorepo uses NPM v7 workspaces (make sure v7 is installed when used with Node.js v14.)