Socket
Socket
Sign inDemoInstall

postcss-selector-parser

Package Overview
Dependencies
3
Maintainers
4
Versions
56
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    postcss-selector-parser

> Selector parser with built in methods for working with selector strings.


Version published
Maintainers
4
Install size
219 kB
Created

Package description

What is postcss-selector-parser?

The postcss-selector-parser npm package is a parser that helps in transforming CSS selectors. It provides a rich API to analyze and manipulate CSS selectors programmatically. This package is particularly useful for tasks related to CSS processing, such as linting, optimization, and custom transformations.

What are postcss-selector-parser's main functionalities?

Parsing and transforming selectors

This feature allows for the parsing and transformation of CSS selectors. In the provided code sample, all 'h1' tags in a selector are changed to 'h2' tags.

const parser = require('postcss-selector-parser');
const transform = selectors => {
  selectors.walkTags(tag => {
    if (tag.value === 'h1') {
      tag.value = 'h2';
    }
  });
};
const transformed = parser(transform).processSync('h1.class');

Extracting classes from selectors

This feature demonstrates how to extract class names from a selector. The code sample extracts 'class1' and 'class2' from the selector string '.class1.class2'.

const parser = require('postcss-selector-parser');
const extractClasses = selector => {
  const classes = [];
  parser(selectors => {
    selectors.walkClasses(classNode => {
      classes.push(classNode.value);
    });
  }).processSync(selector);
  return classes;
};
const classes = extractClasses('.class1.class2');

Working with pseudo classes

This feature focuses on manipulating pseudo classes within selectors. In the example, ':hover' pseudo classes are replaced with ':focus'.

const parser = require('postcss-selector-parser');
const transformPseudo = selector => {
  return parser(selectors => {
    selectors.walkPseudos(pseudo => {
      if (pseudo.value === ':hover') {
        pseudo.value = ':focus';
      }
    });
  }).processSync(selector);
};
const result = transformPseudo('a:hover');

Other packages similar to postcss-selector-parser

Changelog

Source

5.0.0-rc.0

This release has BREAKING CHANGES that were required to fix regressions in 4.0.0 and to make the Combinator Node API consistent for all combinator types. Please read carefully.

Summary of Changes

  • The way a descendent combinator that isn't a single space character (E.g. .a .b) is stored in the AST has changed.
  • Named Combinators (E.g. .a /for/ .b) are now properly parsed as a combinator.
  • It is now possible to look up a node based on the source location of a character in that node and to query nodes if they contain some character.
  • Several bug fixes that caused the parser to hang and run out of memory when a / was encountered have been fixed.
  • The minimum supported version of Node is now v6.0.0.

Changes to the Descendent Combinator

In prior releases, the value of a descendant combinator with multiple spaces included all the spaces.

  • .a .b: Extra spaces are now stored as space before.
    • Old & Busted:
      • combinator.value === " "
    • New hotness:
      • combinator.value === " " && combinator.spaces.before === " "
  • .a /*comment*/.b: A comment at the end of the combinator causes extra space to become after space.
    • Old & Busted:
      • combinator.value === " "
      • combinator.raws.value === " /*comment/"
    • New hotness:
      • combinator.value === " "
      • combinator.spaces.after === " "
      • combinator.raws.spaces.after === " /*comment*/"
  • .a<newline>.b: whitespace that doesn't start or end with a single space character is stored as a raw value.
    • Old & Busted:
      • combinator.value === "\n"
      • combinator.raws.value === undefined
    • New hotness:
      • combinator.value === " "
      • combinator.raws.value === "\n"

Support for "Named Combinators"

Although, nonstandard and unlikely to ever become a standard, combinators like /deep/ and /for/ are now properly supported.

Because they've been taken off the standardization track, there is no spec-official name for combinators of the form /<ident>/. However, I talked to Tab Atkins and we agreed to call them "named combinators" so now they are called that.

Before this release such named combinators were parsed without intention and generated three nodes of type "tag" where the first and last nodes had a value of "/".

  • .a /for/ .b is parsed as a combinator.
    • Old & Busted:
      • root.nodes[0].nodes[1].type === "tag"
      • root.nodes[0].nodes[1].value === "/"
    • New hotness:
      • root.nodes[0].nodes[1].type === "combinator"
      • root.nodes[0].nodes[1].value === "/for/"
  • .a /F\6fR/ .b escapes are handled and uppercase is normalized.
    • Old & Busted:
      • root.nodes[0].nodes[2].type === "tag"
      • root.nodes[0].nodes[2].value === "F\\6fR"
    • New hotness:
      • root.nodes[0].nodes[1].type === "combinator"
      • root.nodes[0].nodes[1].value === "/for/"
      • root.nodes[0].nodes[1].raws.value === "/F\\6fR/"

Source position checks and lookups

A new API was added to look up a node based on the source location.

const selectorParser = require("postcss-selector-parser");
// You can find the most specific node for any given character
let combinator = selectorParser.astSync(".a > .b").atPosition(1,4);
combinator.toString() === " > ";
// You can check if a node includes a specific character
// Whitespace surrounding the node that is owned by that node
// is included in the check.
[2,3,4,5,6].map(column => combinator.isAtPosition(1, column));
// => [false, true, true, true, false]

Readme

Source

postcss-selector-parser Build Status

Selector parser with built in methods for working with selector strings.

Install

With npm do:

npm install postcss-selector-parser

Quick Start

const parser = require('postcss-selector-parser');
const transform = selectors => {
    selectors.walk(selector => {
        // do something with the selector
        console.log(String(selector))
    });
};

const transformed = parser(transform).processSync('h1, h2, h3');

To normalize selector whitespace:

const parser = require('postcss-selector-parser');
const normalized = parser().processSync('h1, h2, h3', {lossless: false});
// -> h1,h2,h3

Async support is provided through parser.process and will resolve a Promise with the resulting selector string.

API

Please see API.md.

Credits

  • Huge thanks to Andrey Sitnik (@ai) for work on PostCSS which helped accelerate this module's development.

License

MIT

FAQs

Last updated on 04 May 2018

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc