This package provides a JavaScript implementation of `querySelectorAll`, designed to offer consistent DOM querying functionality across various environments, including Node.js (with `jsdom`) and older browser contexts. The current stable version is 2.0.0, released in August 2019. The project exhibits a slow release cadence, with no substantial updates since its last major version. Its key differentiator is providing a polyfill-like solution for `querySelectorAll` where native implementations might be absent or incomplete, ensuring broader compatibility for selector-based DOM manipulation. It serves as a foundational utility for projects requiring reliable CSS selector-based element retrieval outside of modern browser engines.
npm install query-selectorVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to use `query-selector` within a Node.js environment by integrating it with `jsdom` to provide a document context. It shows both the native `querySelectorAll` (if available in the JSDOM instance) and the package's implementation, highlighting its usage and expected output.
For browser environments with native `querySelectorAll` support, prefer the native implementation. Use this package primarily for environments lacking native support or for specific polyfill requirements.
Thoroughly test complex or newer CSS selectors when using this package. If specific modern selectors are critical, consider alternative, more actively maintained DOM manipulation libraries or ensure a modern browser environment.
Update all CommonJS `require` statements from `const querySelectorAll = require('query-selector');` to `const querySelectorAll = require('query-selector').default;`.Convert the `NodeList` to an Array when array methods are needed: `Array.from(querySelectorAll('.selector'))` or `[...querySelectorAll('.selector')]`.Change `const querySelectorAll = require('query-selector');` to `const querySelectorAll = require('query-selector').default;`Ensure you are using `import querySelectorAll from 'query-selector';` for default imports, or verify your transpilation configuration correctly handles CommonJS default exports for modules like this.
Always check the `length` property of the returned `NodeList` before attempting to access elements by index: `const elements = querySelectorAll('.my-selector'); if (elements.length > 0) { console.log(elements[0].innerHTML); }`