1

I need to be able to read the available css classes of a loaded web page. Not classes that are assigned to DOM elements, but classes that are defined in the CSS. Is this possible with javascript, or specifically jQuery?

I'm attempting a hackish way to override the columns built into the CMS I'm using (concrete5), so bear with me. On load, there will be a number of divs with certain inline percentage widths, such as style="width: 27%;". In my css, there are a number of classes for a grid system, such as .one, .two, .three, etc. that I want to match to these divs.

For example, I have 3 css classes here:

.one { width: 8.3333%; }
.two { width: 16.6667%; }
.three { width: 25%; }

One of my divs has an inline style of width: 22%;. I want to assign it the class that it most closely matches, which is .three in this case, and remove the inline style programmatically. Is there a way for me to read what the styles of .one, .two, .three, etc are when they're not attached to an element, in other words, read them directly from the css? I want to avoid having to hard-code these values in since they could change.

Tanner Semerad
  • 12,472
  • 12
  • 40
  • 49

1 Answers1

1

The width of a CSS class can be obtained like this:

function getClassWidth(className) {
    var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
    for (var i = 0; i < classes.length; i++) {
        if (classes[i].selectorText == className) {
            return classes[i].style.getPropertyValue("width");
        }
    }
}

getClassWidth('.one'); // Would return the string "8.3333%"

Solution based on this answer.

Community
  • 1
  • 1
David Pärsson
  • 6,038
  • 2
  • 37
  • 52