Skip to content

Instantly share code, notes, and snippets.

@domenic
Last active December 18, 2015 23:49
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save domenic/5864658 to your computer and use it in GitHub Desktop.
Save domenic/5864658 to your computer and use it in GitHub Desktop.
class Elements extends Array
import { absolutizeRelativeSelectorList } from "http://dev.w3.org/csswg/selectors/#absolutizing";
// Assume JSIDL conversions have been applied already,
// i.e. we don't do `selectors = String(selectors)` manually.
class Elements extends Array {
query(selectors) {
return this.queryAll(selectors)[0]; // highly inefficient obviously, but clear semantics
}
queryAll(selectors) {
const absolutized = absolutizeRelativeSelectorList(selectors);
// TODO: instead of `querySelectorAll` possibly use `[[QuerySelectorAll]]` internal
// implementation, see
// http://lists.w3.org/Archives/Public/public-script-coord/2013JulSep/0350.html
const finder = element => this.constructor.from(element.querySelectorAll(absolutized));
// `allFound` is now an `Elements` but it contains `Elements` instances; we need to flatten this out.
// My kingdom for an `Array.prototype.flatMap`!
const allFound = this.map(finder);
// Note that we are concating `Elements` with other `Elements` so it works fine.
const flattened = allMatching.reduce((a, b) => a.concat(b));
return flattened;
}
}
class Elements extends Array {
Elements queryAll(ToString selectors?)
Element query(ToString selectors?)
}
@rwaldron
Copy link

rwaldron commented Apr 8, 2014

This is lovely

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment