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";
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";
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.