Cross-Environment querySelectorAll Implementation

2.0.0 · maintenance · verified Sun Apr 19

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.

Common errors

Warnings

Install

Imports

Quickstart

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.

const querySelectorAll = require('query-selector').default;
const { JSDOM } = require('jsdom');

// Create a JSDOM environment for Node.js to simulate a browser DOM
const dom = new JSDOM('<html><body><div id="t"><span>1</span><span>2</span></div></body></html>');
const doc = dom.window.document;

console.log('--- Using native doc.querySelectorAll ---');
const nativeElements = doc.querySelectorAll('#t span');
console.log('Native result length:', nativeElements.length);
console.log('Native first element innerHTML:', nativeElements[0].innerHTML);

console.log('\n--- Using query-selector package ---');
const customElements = querySelectorAll('#t span', doc);
console.log('Custom result length:', customElements.length);
console.log('Custom first element innerHTML:', customElements[0].innerHTML);

// Demonstrates calling the custom querySelectorAll with a specific context (the document)
// The output should be identical, showcasing its polyfill capability.
// In a browser, the 'doc' argument would often be 'document' or 'this'.

view raw JSON →