A CSS selector set with fast DOM element matching.
Background in this post (as well as an alternative implementation) by josh.
Here we provide a faster, more modular, UMD-compliant implementation of Selector Set.
var set = new SelectorSet()
Add a selector to the set.
selector {String}
- The selector to add.data ...
- Arbitrary number of additional parameters which will be added with the selector as associated data.
Returns the set instance, so remove
/ add
calls can be chained.
Remove a selector (+data) from the set.
selector {String}
- The selector to remove.data ...
- Arbitrary number of additional parameters for more specific removal of selectors.
Returns the set instance, so remove
/ add
calls can be chained.
Matches DOM elements to selectors in the set.
element ... {DOMElement}
- The DOM elements to match.
Returns array of arrays. Each sub-array is a selector that matches the elements
- the data this selector was added with.
matchesSelector
is a function which checks if an element matches a selector.
It's used internally by SelectorSet
, but exposed through the prototype to
allow overriding with a custom method.
It takes the following parameters:
element {DOMElement}
- The element to matchselector {String}
- The selector to match against
It returns true
if the element matches the selector. false
otherwise.
The default implementation tries to use the browser's native match
or
matchesSelector
DOM functions, or a polyfill
for older browsers.
It can be overridden by:
-
Overriding the prototype, thus modifying all instances of SelectorSet:
SelectorSet.prototype.matchesSelector = customFunction; var sSet = new SelectorSet();
-
Overriding the instance, thus modifying a specific instance of SelectorSet:
var sSet = new SelectorSet(); sSet.matchesSelector = customFunction;
- Node:
0.
npm install mu-selector-set
0.var SelectorSet = require('mu-selector-set');
- AMD (install with bower):
0.
bower install mu-selector-set
0.require(['mu-selector-set'], function(SelectorSet){ /* ... */ });
Run tests with npm test
.
Run coverage analysis with npm run coverage
(coverage report is saved to
./coverage
).
var el = $("<div id='foo' class='bar'/>").get(0),
sSet = new SelectorSet();
sSet.add("div")
.add(".bar", 123, 456)
.add(".baz", 123, "abc")
.add("#foo.bar")
.add("*");
sSet.matches(el);
//[ [ '#foo.bar' ],
// [ '.bar', 123, 456 ],
// [ 'div' ],
// [ '*' ] ]
Multiple elements:
var el1 = $("<div id='foo'/>").get(0),
el2 = $("<div class='bar'/>").get(0),
sSet = new SelectorSet();
sSet.add("div")
.add(".bar", 123, 456)
.add(".baz", 123, "abc")
.add("#foo.bar, .bar.baz")
.add("*");
set.matches(el1, el2);
//[ [ 'div' ],
// [ '*' ],
// [ '.bar', 123, 456 ] ]