2

Is there any possiblity get all defined CSS classes matching a pattern?

For example if you have some CSS rules defined like:

.my-custom-class-one {}
.my-custom-class-two {}
.my-custom-class-three {}

I'd like to have something like:

console.log( getClassNamesByPattern('my-custom-class-*') );

returning a list of the matching classes:

[ 'my-custom-class-one', 'my-custom-class-two', 'my-custom-class-three' ]

There is no markup matching those selectors (yet). Actually that's what i'd like to create...

I thought maybe something like getComputedStyles would do the trick, but since it expects an element, which doesn't exists, it doesn't seem to be of much use...

gherkins
  • 14,603
  • 6
  • 44
  • 70
  • Are you using jquery on your site? If so, then using a filter might be a solution for you. – Fisch Aug 23 '13 at 08:24

1 Answers1

2

The following would be a solution:

CSS

.my-custom-class-one {}
.my-custom-class-two {}
.my-custom-class-three {}

JS

function getClassNamesByPattern(pattern) {
    var selectors = {};

    for (var i = 0; i < document.styleSheets.length; i++) {
        var classes = document.styleSheets[i].rules || document.styleSheets[i].cssRules;
        for (var x = 0; x < classes.length; x++) {
            if (undefined !== classes[x].selectorText && null !== classes[x].selectorText.match(new RegExp('\\.' + pattern.replace(/([^\s])\*/, '$1[^ ]+'), 'g'))) {
                selectors[classes[x].selectorText] = classes[x].selectorText;
            }
        }
    }

    return Object.keys(selectors);
}

console.log(getClassNamesByPattern('my-custom-class-*'));

as seen here all css classes in page using js

...wondering how that might perform on pages with lots of style rules, though.

Community
  • 1
  • 1
gherkins
  • 14,603
  • 6
  • 44
  • 70
  • I would probably use something like: `classes[x].selectorText.match(new RegExp('\\.'+pattern.replace(/([^\s])\*/,'$1[^ ]+'),'g'))` – MDEV Aug 22 '13 at 10:58
  • I suppose that check for the existence of `classes[x].selectorText` may be needed, since [not all CSSrule subtypes](https://developer.mozilla.org/en-US/docs/Web/API/CSSRule?redirectlocale=en-US&redirectslug=DOM%2FcssRule) have such property. Otherwise it's the only possible solution to find the CSS rules declared but not used by actual DOM elements, AFAIK. – Ilya Streltsyn Aug 22 '13 at 10:59
  • @MarkResølved I've updated my comment as well - was flawed. Might want to change to the new version – MDEV Aug 22 '13 at 11:04
  • 1
    Shouldn't you also loop through `document.styleSheets` instead of just checking the first one: `document.styleSheets[0]`? – André Dion Aug 22 '13 at 11:21
  • This fails in Firefox with the error "Operation is Insecure". Firefox prevents cross-domain CSS traversal. If you need to find some custom CSS classes, you may need to restrict yourself to your own CSS, which this solution doesn't do. – gene b. Oct 29 '17 at 15:46