CSS selectors implemented in javascript
This library does not depend on any javascript DOM parser and can be used in either browser or node environment.
It can work with native DOM in browser, with parse5 or any other library.
$ npm install @slicky/query-selector
First you will need to implement few methods, which will be used by this library to read the DOM.
Example of the simplest document walker:
import {IDocumentWalker, DocumentNode, DocumentParent} from '@slicky/query-selector';
class CustomDocumentWalker implements IDocumentWalker
{
public getNodeName(node: DocumentNode): string
{
return node.nodeName;
}
public isElement(node: DocumentNode): boolean
{
return node.type === 'string';
}
public isString(node: DocumentNode): boolean
{
return node.type === 'string';
}
public getParentNode(node: DocumentNode): DocumentParent
{
return node.parentNode;
}
public getChildNodes(parent: DocumentParent): Array<DocumentNode>
{
return parent.childNodes;
}
public getAttribute(node: DocumentNode, name: string): string
{
return node.attributes[name];
}
}
import {Matcher} from '@slicky/query-selector';
let matcher = new Matcher(new CustomDocumentWalker);
let dom = loadCustomDOM();
let element = matcher.querySelector(dom, 'div a.btn:first-child'); // one element
let elements = matcher.querySelectorAll(dom, 'a.btn'); // array of elements
let matches = matcher.matches(element, 'a.btn'); // true
querySelector
: similar to Document.querySelector()querySelectorAll
: similar to Document.querySelectorAll()matches
: similar to Element.matches()
- Type selector (
div
) - Class selector (
.btn
) - ID selector (
#header
) - Attribute selectors (
[attr]
, ...) - Adjacent sibling selector (
span + i
) - General sibling selector (
span ~ i
) - Child selector (
span > i
) - Descendant selector (
span i
) - Empty (
:empty
) - First child (
:first-child
) - First of type (
:first-of-type
) - Last child (
:last-child
) - Last of type (
:last-of-type
) - Not (
:not()
) - Before (
::before
) - After (
::after
)