specificity.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. module.exports = function specificity(simpleSelector) {
  2. var A = 0;
  3. var B = 0;
  4. var C = 0;
  5. simpleSelector.children.each(function walk(node) {
  6. switch (node.type) {
  7. case 'SelectorList':
  8. case 'Selector':
  9. node.children.each(walk);
  10. break;
  11. case 'IdSelector':
  12. A++;
  13. break;
  14. case 'ClassSelector':
  15. case 'AttributeSelector':
  16. B++;
  17. break;
  18. case 'PseudoClassSelector':
  19. switch (node.name.toLowerCase()) {
  20. case 'not':
  21. node.children.each(walk);
  22. break;
  23. case 'before':
  24. case 'after':
  25. case 'first-line':
  26. case 'first-letter':
  27. C++;
  28. break;
  29. // TODO: support for :nth-*(.. of <SelectorList>), :matches(), :has()
  30. default:
  31. B++;
  32. }
  33. break;
  34. case 'PseudoElementSelector':
  35. C++;
  36. break;
  37. case 'TypeSelector':
  38. // ignore universal selector
  39. if (node.name.charAt(node.name.length - 1) !== '*') {
  40. C++;
  41. }
  42. break;
  43. }
  44. });
  45. return [A, B, C];
  46. };