With node-css-selector-parser, we can parse a CSS selector and based on a result type analyze class names used with a dot (e.g. .myclass) and class names used inside the attribute selector (e.g. [class*=test]):// setup up CSS selector parservar CssSelectorParser = require('css-selector-parser').CssSelectorParservar parser = new CssSelectorParser()parser.registerSelectorPseudos('has', 'contains')parser.registerNestingOperators('>', '+', '~')parser.registerAttrEqualityMods('^', '$', '*', '~')parser.enableSubstitutes()function extractClassNames (rule) { var classNames = [] // extract class names defined with ".", e.g. .myclass if (rule.classNames) { classNames.push.apply(classNames, rule.classNames) } // extract class names defined in attributes, e.g. [class*=myclass] if (rule.attrs) { rule.attrs.forEach(function (attr) { if (attr.name === 'class') { classNames.push(attr.value) } }) } return classNames}module.exports = function (cssSelector) { try { var result = parser.parse(cssSelector) } catch (err) { // ignore parsing errors - we don't want it to fail miserably on a target machine during a ESLint run console.log('Parsing CSS selector: "' + cssSelector + '". ' + err) return [] } // handling empty inputs if (!result) { return [] } var classNames = [] if (result.type === 'ruleSet') { var rule = result.rule while (rule) { classNames.push.apply(classNames, extractClassNames(rule)) rule = rule.rule } } else if (result.type === 'selectors' && result.selectors) { result.selectors.forEach(function (selector) { classNames.push.apply(classNames, extractClassNames(selector.rule)) }) } return classNames}( standard 代码样式-例如,在行的结尾)(standard code style is used - hence, for instance, no ; at the end of the lines)事实证明,这对我有用,并希望对其他有类似问题的人有所帮助.请注意,在此状态下,此代码还将提取传递到^=,$=和*=的部分类值,理想情况下,应将这些部分类值跳过.This proved to work for me and hopefully would help others with a similar problem. Note that in this state this code would also extract the partial class values passed into the ^=, $= and *= which ideally need to be skipped. 这篇关于如何从CSS选择器中提取类名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-11 13:18