1

I'm trying to iterate through CSS styles. For example I get a style like this:

document.styleSheets[0].cssRules[10].style

That returns a CSSStyleRule which is an object with both integer and string keys.

The integer and .length keys can be used to iterate through the property assignments in the style, and each one gives the name of the property, for example:

document.styleSheets[0].cssRules[10].style[0] == "max-height"

The string keys give access to the actual actual text for the style like this:

document.styleSheets[0].cssRules[10].style["maxHeight"] == "100px"

So in theory it is easy to iterate through all the properties. But notice the maddening change from max-height to maxHeight! How can I deal with this? How do I even know what this mapping is? Do I just have to write a function that converts every -a to A and so on?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Timmmm
  • 88,195
  • 71
  • 364
  • 509
  • 1
    is this what you're looking for? http://stackoverflow.com/questions/2531737/javascript-incapable-of-getting-elements-max-height-via-element-style-maxheight – Bhojendra Rauniyar Jan 28 '15 at 14:07
  • possible duplicate of [How to get an HTML element's style values in javascript?](http://stackoverflow.com/questions/2664045/how-to-get-an-html-elements-style-values-in-javascript) – TylerH Jan 28 '15 at 14:42
  • Well it's not really a duplicate because those are about getting a specific style, whereas this is about iterating through the styles. However the answer to my question was found in the answer to Bhojendra's linked question. – Timmmm Jan 28 '15 at 14:46
  • This can help - https://stackoverflow.com/a/14544497/104380 – vsync Jun 10 '18 at 08:26

1 Answers1

0

I ended up using this function to change the case:

function camelCaseCssName(str) {
    var ret = "";
    for (var i = 0; i < str.length; ++i) {
        if (str[i] == '-') {
            if (i < str.length - 1) {
                ret += str[i+1].toUpperCase();
                ++i;
            }
        } else {
            ret += str[i];
        }           
    }
    return ret;
}

The link Bhojendra posted also contains this version which I haven't tested, but it is a lot shorter:

styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
  return letter.toUpperCase();
});
Timmmm
  • 88,195
  • 71
  • 364
  • 509