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

1
  • Are you using jquery on your site? If so, then using a filter might be a solution for you. Commented Aug 23, 2013 at 8:24

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I would probably use something like: classes[x].selectorText.match(new RegExp('\\.'+pattern.replace(/([^\s])\*/,'$1[^ ]+'),'g'))
I suppose that check for the existence of classes[x].selectorText may be needed, since not all CSSrule subtypes have such property. Otherwise it's the only possible solution to find the CSS rules declared but not used by actual DOM elements, AFAIK.
@MarkResølved I've updated my comment as well - was flawed. Might want to change to the new version
Shouldn't you also loop through document.styleSheets instead of just checking the first one: document.styleSheets[0]?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.