css-selector-parser

  • Version 3.2.0
  • Published
  • 183 kB
  • No dependencies
  • MIT license

Install

npm i css-selector-parser
yarn add css-selector-parser
pnpm add css-selector-parser

Overview

Powerful and compliant CSS selector parser.

Index

Variables

variable ast

const ast: AstFactory;
  • AST structure generators and matchers. For instance, ast.selector({rules: [...]}) creates AstSelector and ast.isSelector(...) checks if AstSelector was specified.

    Example 1

    // Represents CSS selector: ns|div#user-34.user.user-active[role="button"]:lang(en)::before > * const selector = ast.selector({ rules: [ ast.rule({ items: [ ast.tagName({name: 'div', namespace: ast.namespaceName({name: 'ns'})}), ast.id({name: 'user-34'}), ast.className({name: 'user'}), ast.className({name: 'user-active'}), ast.attribute({ name: 'role', operator: '=', value: ast.string({value: 'button'}) }), ast.pseudoClass({ name: 'lang', argument: ast.string({value: 'en'}) }), ast.pseudoElement({name: 'before'}) ], nestedRule: ast.rule({combinator: '>', items: [ast.wildcardTag()]}) }) ] }); console.log(ast.isSelector(selector)); // prints true console.log(ast.isRule(selector)); // prints false

Functions

function createParser

createParser: (options?: {
syntax?: CssLevel | SyntaxDefinition;
substitutes?: boolean;
strict?: boolean;
modules?: CssModule[];
}) => Parser;
  • Creates a parse function to be used later to parse CSS selectors.

function render

render: (entity: AstEntity) => string;
  • Renders CSS Selector AST back to a string.

    Example 1

    import {ast, render} from 'css-selector-parser';

    const selector = ast.selector({ rules: [ ast.rule({ items: [ ast.tagName({name: 'a'}), ast.id({name: 'user-23'}), ast.className({name: 'user'}), ast.pseudoClass({name: 'visited'}), ast.pseudoElement({name: 'before'}) ] }) ] });

    console.log(render(selector)); // a#user-23.user:visited::before

Interfaces

interface AstAttribute

interface AstAttribute {}
  • Attribute selector. Generated by .

    Example 1

    "[role='button' i]"

property caseSensitivityModifier

caseSensitivityModifier?: string;
  • Comparison case sensitivity modifier (i.e. "i" in case if "[role='button' i]").

property name

name: string;
  • Attribute name (i.e. "href" in case if "[href]").

property namespace

namespace?: AstNamespaceName | AstWildcardNamespace | AstNoNamespace;
  • Namespace according to https://drafts.csswg.org/selectors/#attrnmsp.

property operator

operator?: string;
  • Comparison operator (i.e. "|=" in case if "[role|=button]").

property type

type: 'Attribute';

    property value

    value?: AstString | AstSubstitution;
    • Comparison value (i.e. "button" in case if "[role=button]").

    interface AstClassName

    interface AstClassName {}
    • Class name condition. Matches by class attribute value. Generated by . https://developer.mozilla.org/en-US/docs/Web/CSS/ID_selectors

      Example 1

      ".user"

    property name

    name: string;
    • ID name. I.e. .user -> "user".

    property type

    type: 'ClassName';

      interface AstFactory

      interface AstFactory extends AstFactoryBase {}
      • AST structure generators and matchers. For instance, ast.selector({rules: [...]}) creates AstSelector and ast.isSelector(...) checks if AstSelector was specified.

        Example 1

        // Represents CSS selector: ns|div#user-34.user.user-active[role="button"]:lang(en)::before > * const selector = ast.selector({ rules: [ ast.rule({ items: [ ast.tagName({name: 'div', namespace: ast.namespaceName({name: 'ns'})}), ast.id({name: 'user-34'}), ast.className({name: 'user'}), ast.className({name: 'user-active'}), ast.attribute({ name: 'role', operator: '=', value: ast.string({value: 'button'}) }), ast.pseudoClass({ name: 'lang', argument: ast.string({value: 'en'}) }), ast.pseudoElement({name: 'before'}) ], nestedRule: ast.rule({combinator: '>', items: [ast.wildcardTag()]}) }) ] }); console.log(ast.isSelector(selector)); // prints true console.log(ast.isRule(selector)); // prints false

      interface AstFormula

      interface AstFormula {}
      • Pseudo-class formula value. a is multiplier of n and b us added on top. Formula: an + b. For instance :nth-child(2n + 1) -> {type: 'AstPseudoClass'..., argument: {type: 'Formula', a: 2, b: 1}}. Generated by .

        See Also

        • https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child#functional_notation

      property a

      a: number;
      • Multiplier of n.

      property b

      b: number;
      • Constant added to a*n.

      property type

      type: 'Formula';

        interface AstFormulaOfSelector

        interface AstFormulaOfSelector {}
        • Pseudo-class formula of selector value. a is multiplier of n and b us added on top. Formula: an + b. Formula is followed by of keyword and then goes a CSS selector. For instance :nth-child(2n + 1 of div) -> {type: 'AstPseudoClass'..., argument: {type: 'FormulaOfSelector', a: 2, b: 1, selector: {type: 'Selector', rules: [{type: 'Rule', items: [{type: 'TagName', name: 'div'}]}]}}}. Generated by .

          See Also

          • https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child#functional_notation

        property a

        a: number;
        • Multiplier of n.

        property b

        b: number;
        • Constant added to a*n.

        property selector

        selector: AstRule;
        • Selector that goes after formula (i.e. "div -> span" in case of ":nth-child(2n + 1 of div > span)"

        property type

        type: 'FormulaOfSelector';

          interface AstId

          interface AstId {}
          • ID condition. Matches by id attribute value. Generated by . https://developer.mozilla.org/en-US/docs/Web/CSS/ID_selectors

            Example 1

            "#root"

          property name

          name: string;
          • ID name. I.e. #root -> "root".

          property type

          type: 'Id';

            interface AstNamespaceName

            interface AstNamespaceName {}
            • Named namespace declaration (i.e. ns|div). Generated by .

              See Also

              • https://drafts.csswg.org/css-namespaces-3/#css-qnames

            property name

            name: string;
            • Namespace name (i.e. "ns" in case of "ns|div"). "

            property type

            type: 'NamespaceName';

              interface AstNestingSelector

              interface AstNestingSelector {}
              • CSS Nesting Selector: &. Represents the parent selector in nested CSS. Generated by .

                Example 1

                "&:hover"

                See Also

                • https://www.w3.org/TR/css-nesting-1/#nest-selector

              property type

              type: 'NestingSelector';

                interface AstNoNamespace

                interface AstNoNamespace {}
                • Explicit no-namespace declaration (i.e. |div). Generated by .

                  See Also

                  • https://drafts.csswg.org/css-namespaces-3/#css-qnames

                property type

                type: 'NoNamespace';

                  interface AstPseudoClass

                  interface AstPseudoClass {}
                  • Pseudo-class selector. Generated by .

                    Example 1

                    ":lang(en)"

                    See Also

                    • https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors/Pseudo-classes_and_pseudo-elements

                  property argument

                  argument?:
                  | AstSubstitution
                  | AstSelector
                  | AstString
                  | AstFormula
                  | AstFormulaOfSelector;
                  • Pseudo-class value (i.e. "en" in case of ":lang(en)").

                  property name

                  name: string;
                  • Pseudo-class name (i.e. "hover" in case of ":hover").

                  property type

                  type: 'PseudoClass';

                    interface AstPseudoElement

                    interface AstPseudoElement {}
                    • Pseudo-class selector. Generated by .

                      Example 1

                      "::before"

                      See Also

                      • https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors/Pseudo-classes_and_pseudo-elements

                    property argument

                    argument?: AstSubstitution | AstString | AstSelector;
                    • Pseudo-element value (i.e. "foo" in case of "::part(foo)").

                    property name

                    name: string;
                    • Pseudo-element name (i.e. "before" in case of "::before").

                    property type

                    type: 'PseudoElement';

                      interface AstRule

                      interface AstRule {}
                      • A single CSS rule that contains match conditions. Can nest another rule with or without a combinator (i.e. "div > span"). Generated by .

                      property combinator

                      combinator?: string;
                      • Rule combinator which was used to nest this rule (i.e. ">" in case of "div > span" if the current rule is "span").

                      property items

                      items: (
                      | AstTagName
                      | AstWildcardTag
                      | AstId
                      | AstClassName
                      | AstAttribute
                      | AstPseudoClass
                      | AstPseudoElement
                      | AstNestingSelector
                      )[];
                      • Items of a CSS rule. Can be tag, ids, class names, pseudo-classes and pseudo-elements.

                      property nestedRule

                      nestedRule?: AstRule;
                      • Nested rule if specified (i.e. "div > span").

                      property type

                      type: 'Rule';

                        interface AstSelector

                        interface AstSelector {}
                        • CSS Selector AST root. Contains list of CSS rules (separated by a comma in the input CSS selector string). Generated by .

                        property rules

                        rules: AstRule[];
                        • List of CSS rules. Every rule contains conditions. Selector is considered matched once at least one rule matches.

                        property type

                        type: 'Selector';

                          interface AstString

                          interface AstString {}
                          • String value. Can be used as attribute value of pseudo-class string value. For instance :lang(en) -> {type: 'AstPseudoClass'..., argument: {type: 'String', value: 'en'}}. Generated by .

                          property type

                          type: 'String';

                            property value

                            value: string;
                            • The actual string value.

                            interface AstSubstitution

                            interface AstSubstitution {}
                            • Substitution is not part of CSS spec, but rather a useful extension on top of CSS if you need to pass variables. Generated by .

                            property name

                            name: string;
                            • Substitution name (i.e. "var" in case of "[role=$var]" or ":lang($var)").

                            property type

                            type: 'Substitution';

                              interface AstTagName

                              interface AstTagName {}
                              • Named tag, i.e. "div". Part of CSS Qualified Names. Generated by .

                                See Also

                                • https://developer.mozilla.org/en-US/docs/Web/CSS/Type_selectors

                                • https://drafts.csswg.org/css-namespaces-3/#css-qnames

                              property name

                              name: string;
                              • Tag name, i.e. "div".

                              property namespace

                              namespace?: AstNamespaceName | AstWildcardNamespace | AstNoNamespace;
                              • Namespace according to https://www.w3.org/TR/css3-namespace/.

                              property type

                              type: 'TagName';

                                interface AstWildcardNamespace

                                interface AstWildcardNamespace {}
                                • Wildcard namespace (universal selector): *. Generated by .

                                  See Also

                                  • https://developer.mozilla.org/en-US/docs/Web/CSS/Universal_selectors

                                  • https://drafts.csswg.org/css-namespaces-3/#css-qnames

                                property type

                                type: 'WildcardNamespace';

                                  interface AstWildcardTag

                                  interface AstWildcardTag {}
                                  • Wildcard tag (universal selector): *. Generated by .

                                    See Also

                                    • https://developer.mozilla.org/en-US/docs/Web/CSS/Universal_selectors

                                    • https://drafts.csswg.org/css-namespaces-3/#css-qnames

                                  property namespace

                                  namespace?: AstNamespaceName | AstWildcardNamespace | AstNoNamespace;
                                  • Namespace according to https://www.w3.org/TR/css3-namespace/.

                                  property type

                                  type: 'WildcardTag';

                                    interface ParserError

                                    interface ParserError extends Error {}
                                    • This error is thrown when parser encounters problems in CSS string. On top of the usual error, it has position property to indicate where in the input string the error happened.

                                    property message

                                    message: string;

                                      property name

                                      name: 'ParserError';

                                        property position

                                        position: number;

                                          interface SyntaxDefinition

                                          interface SyntaxDefinition {}
                                          • CSS Selector Syntax Definition can be used to define custom CSS selector parsing rules.

                                          property attributes

                                          attributes?:
                                          | {
                                          /**
                                          * Attribute comparison operator list.
                                          * @example ['=', '~=', '|=', '^=', '$=', '*=']
                                          * @see https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors#syntax
                                          */
                                          operators?: string[];
                                          /**
                                          * How to handle unknown case sensitivity modifiers.
                                          * `accept` - still parse.
                                          * `reject` - throw an error.
                                          */
                                          unknownCaseSensitivityModifiers?: 'accept' | 'reject';
                                          /**
                                          * List of pre-defined case sensitivity modifiers.
                                          * @example ['i', 'I', 's', 'S']
                                          * @see https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors#syntax
                                          */
                                          caseSensitivityModifiers?: string[];
                                          }
                                          | false;
                                          • CSS Attribute Selector.

                                            Example 1

                                            [href="#"]

                                            See Also

                                            • https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors/Attribute_selectors

                                          property baseSyntax

                                          baseSyntax?: CssLevel;
                                          • When specified, syntax will be based on the specified predefined CSS standard. If not specified, syntax will be defined from scratch.

                                          property classNames

                                          classNames?: boolean;
                                          • CSS Class Names

                                            Example 1

                                            .element.highlighted

                                            See Also

                                            • https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors/Type_Class_and_ID_Selectors

                                          property combinators

                                          combinators?: string[];
                                          • CSS selector rule nesting combinators.

                                            Example 1

                                            div.class > span

                                            See Also

                                            • https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors/Combinators

                                          property ids

                                          ids?: boolean;
                                          • CSS IDs (yes, there can be multiple).

                                            Example 1

                                            #root#root

                                            See Also

                                            • https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors/Type_Class_and_ID_Selectors

                                          property modules

                                          modules?: CssModule[];
                                          • Additional CSS modules to include in the syntax definition. These are specific CSS modules that add new selectors or modify existing ones.

                                            Example 1

                                            ['css-position-4', 'css-scoping-1']

                                          property namespace

                                          namespace?:
                                          | {
                                          /**
                                          * Allows using wildcard (*).
                                          */
                                          wildcard?: boolean;
                                          }
                                          | boolean;
                                          • CSS3 Namespaces.

                                            Example 1

                                            ns|div

                                            See Also

                                            • https://www.w3.org/TR/css3-namespace/

                                          property nestingSelector

                                          nestingSelector?: boolean;
                                          • CSS Nesting Selector (&). Represents the parent selector in nested CSS.

                                            Example 1

                                            &:hover

                                            See Also

                                            • https://www.w3.org/TR/css-nesting-1/#nest-selector

                                          property pseudoClasses

                                          pseudoClasses?:
                                          | {
                                          /**
                                          * How to handle unknown pseudo-classes.
                                          * `accept` - still parse.
                                          * `reject` - throw an error.
                                          */
                                          unknown?: 'accept' | 'reject';
                                          /**
                                          * Predefined pseudo-classes.
                                          * @example {NoArgument: ['first-child'], Formula: ['nth-child'], String: ['dir'], Selector: ['not']}
                                          */
                                          definitions?: {
                                          [K in PseudoClassType]?: string[];
                                          };
                                          }
                                          | false;
                                          • CSS Pseudo-classes.

                                            Example 1

                                            :nth-child(2n+1)

                                            See Also

                                            • https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors/Pseudo-classes_and_pseudo-elements

                                          property pseudoElements

                                          pseudoElements?:
                                          | {
                                          /**
                                          * How to handle unknown pseudo-elements.
                                          * `accept` - still parse.
                                          * `reject` - throw an error.
                                          */
                                          unknown?: 'accept' | 'reject';
                                          /**
                                          * In the past pseudo selements were defined starting with a single colon.
                                          * Later this notation changed to double colon.
                                          */
                                          notation?: 'singleColon' | 'doubleColon' | 'both';
                                          /**
                                          * List of predefined pseudo-elements. If string array is specified, the pseudo-elements are assumed to be
                                          * NoArgument.
                                          * @example ['before', 'after']
                                          * @example {NoArgument: ['before', 'after'], String: ['highlight'], Selector: ['slotted']}
                                          */
                                          definitions?:
                                          | string[]
                                          | {
                                          [K in PseudoElementType]?: string[];
                                          };
                                          }
                                          | false;
                                          • CSS Pseudo-elements.

                                            Example 1

                                            ::before

                                            See Also

                                            • https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors/Pseudo-classes_and_pseudo-elements

                                          property tag

                                          tag?:
                                          | {
                                          /**
                                          * Allows using wildcard (*).
                                          */
                                          wildcard?: boolean;
                                          }
                                          | boolean;
                                          • CSS Tag (type).

                                            Example 1

                                            div

                                            See Also

                                            • https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors/Type_Class_and_ID_Selectors

                                          Type Aliases

                                          type AstEntity

                                          type AstEntity =
                                          | AstSelector
                                          | AstRule
                                          | AstTagName
                                          | AstWildcardTag
                                          | AstId
                                          | AstClassName
                                          | AstNamespaceName
                                          | AstWildcardNamespace
                                          | AstNoNamespace
                                          | AstNestingSelector
                                          | AstSubstitution
                                          | AstString
                                          | AstFormula
                                          | AstFormulaOfSelector
                                          | AstPseudoClass
                                          | AstAttribute
                                          | AstPseudoElement;
                                          • One of CSS AST entity types.

                                          type CssLevel

                                          type CssLevel =
                                          | 'css1'
                                          | 'css2'
                                          | 'css3'
                                          | 'selectors-3'
                                          | 'selectors-4'
                                          | 'latest'
                                          | 'progressive';

                                            type CssModule

                                            type CssModule = keyof typeof cssModules;
                                            • CSS Module name.

                                              Example 1

                                              'css-position-3'

                                              Example 2

                                              'css-scoping-1'

                                            type Parser

                                            type Parser = (input: string) => AstSelector;
                                            • Parses CSS selector string and returns CSS selector AST.

                                              Throws

                                              {ParserError}

                                            Package Files (5)

                                            Dependencies (0)

                                            No dependencies.

                                            Dev Dependencies (19)

                                            Peer Dependencies (0)

                                            No peer dependencies.

                                            Badge

                                            To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                            You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/css-selector-parser.

                                            • Markdown
                                              [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/css-selector-parser)
                                            • HTML
                                              <a href="https://www.jsdocs.io/package/css-selector-parser"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>