0

Is there a way to add a selector to an existing rule with Postcss API? Something like myRule.addSelector(".newSelector")?

Currently I have to do this:

myRule.selector = myRule.selector ? myRule.selector + ", .newSelector" : ".newSelector";
François Romain
  • 13,617
  • 17
  • 89
  • 123

1 Answers1

0

You can use rule.selectors, which is a property with a getter that returns an array of selectors (generated from the rule.selector string), and a setter that takes an array of selectors (and overwrites the rule.selector string).

var sels = myRule.selectors; //save the getter returned array so we can modify it with push.
sels.push('.newSelector'); //push returns the new length not the array, that's why we had to save the array in sels.
myRule.selectors = sels; //the setter will join the array elements and overwrite myRule.selector

A much shorter version using concat (because concat returns a new array).

myRule.selectors = myRule.selectors.concat('.newSelector');

See the PostCSS source here.

Adrien
  • 667
  • 6
  • 7
  • `var sels = myRule.selectors` returns an error `TypeError: Cannot read property 'length' of undefined` if no selectors are defined. – François Romain Apr 11 '16 at 00:22