Skip to content

niksy/postcss-query-ast

Repository files navigation

postcss-query-ast

Build Status

Query PostCSS AST with CSS selectors.

Supported selectors are:

In addition to standard selectors, there are also custom selectors:

  • Attribute selector with regular expression: [attr="/^value$/i"]

Install

npm install postcss-query-ast --save

Usage

Querying AST from following CSS will give us only body rule with jackie ID attribute.

body {
	background: red;
}

body#jackie {
	background: hotpink;
}

a {
	background: green;
}
import queryAst from 'postcss-query-ast';

// Assume we have AST
const postcssAst = [];

(async () => {
	const ast = await queryAst('rule[selector="body#jackie"]', postcssAst);

	/* [ Rule {
	    raws: { before: '\n\n', between: ' ', semicolon: true, after: '\n' },
	    type: 'rule',
	    nodes: [ [Declaration] ],
	    parent: 
	     Root {
	       raws: [Object],
	       type: 'root',
	       nodes: [Array],
	       source: [Object],
	       lastEach: 1,
	       indexes: {} },
	    source: { start: [Object], input: [Input], end: [Object] },
	    selector: 'body#jackie',
	    lastEach: 1,
	    indexes: {} } ] */
})();

API

queryAst(query, ast)

Returns: Promise<(Root | Rule | AtRule | Declaration | Comment)[]>

Queries PostCSS with CSS selector.

query

Type: string

CSS selector.

ast

Type: Root

PostCSS AST.

License

MIT © Ivan Nikolić