css-select
raw JSON →A CSS selector compiler and engine that turns CSS selectors into functions to test or find matching elements in a DOM tree. Current stable version is 7.0.0, released as an ESM-only package requiring Node.js >=20.19.0. The engine uses a right-to-left execution model for optimal performance (O(n) vs O(n^(k+1)) for left-to-right engines). It fully implements CSS3 selectors and most CSS4 selectors, with partial jQuery/Sizzle extension support. Ships TypeScript types. Breaking changes in v7 include removal of CommonJS support, removal of deprecated exports (_compileToken, aliases, filters, pseudos), and no more deep imports. Prior major versions include v6 (dual CJS/ESM, pseudos option, `:where` support) and v5 (adapter API changes). Release cadence is periodic; maintained by fb55.
Common errors
error Error: The `_compileToken` export has been removed. Use `_compileUnsafe` instead. ↓
error TypeError: Cannot read properties of undefined (reading 'type') ↓
error SyntaxError: Unexpected token / ↓
Warnings
breaking ESM only in v7+; CommonJS require() does not work. ↓
breaking Deep imports (e.g., 'css-select/lib/...') are no longer permitted since v5. ↓
deprecated Re-exports of aliases, filters, and pseudos are deprecated since v5 and removed in v7. ↓
deprecated _compileToken export is deprecated since v5 and removed in v7. ↓
gotcha Relative selectors are enabled by default: selectors are relative to the passed context (no parent matching above context). ↓
gotcha The default adapter works with domhandler nodes. If using a custom DOM structure, you must provide an adapter object. ↓
Install
npm install css-select yarn add css-select pnpm add css-select Imports
- cssSelect wrong
const cssSelect = require('css-select')correctimport cssSelect from 'css-select' - isTag wrong
import { isTag } from 'css-select/lib/general'correctimport { isTag } from 'css-select' - compile
import { compile } from 'css-select' - filters wrong
const filters = require('css-select/lib/pseudo-selectors/filters')correctimport { filters } from 'css-select'
Quickstart
import cssSelect, { compile } from 'css-select';
import { parseDocument } from 'htmlparser2';
import { getElementsByTagName } from 'domutils';
const html = '<html><body><div class="container"><p id="intro">Hello</p><p>World</p></div></body></html>';
const dom = parseDocument(html);
// Use cssSelect to find elements matching a selector
const paragraphs = cssSelect('p', dom);
console.log('Number of <p> elements:', paragraphs.length);
// Compile a selector into a reusable function
const isContainerDiv = compile('.container');
const container = paragraphs.find(el => el.parent && isContainerDiv(el.parent));
console.log('Parent container tag:', container?.parent?.name || 'N/A');
// With options (e.g., pseudos)
const buttons = cssSelect('button:enabled', dom, { pseudos: { }});
console.log('Buttons:', buttons.length);