Steven Lu
Steven Lu

Reputation: 43437

CSS Style property names -- going from the regular version to the JS property camelCase version and vice versa

Does there exist a provision for obtaining the corresponding names?

A function I'm writing has to both set the style via element.style[propnameCamelCase] and retrieve the existing rendered value via document.defaultView.getComputedStyle(element,'').getPropertyValue(propname-regular), and I can hardly justify having to pass two separate but semantically identical arguments to this function.

I know that for most of them it's a fairly straightforward transcription between camelCase and hyphen-delimited with the same words, so I can use regexes to convert them. But maybe there are a few that are not like this?

Off the top of my head I'm having a hard time figuring out how to deal with the capitalized letters for camel case with regular expressions.

edit: Ah, I could use a function for regex replace, each time I see a hyphen, convert next letter to upper case.

Upvotes: 10

Views: 2567

Answers (3)

brennanyoung
brennanyoung

Reputation: 6524

I'd like to mention that CSSStyleDeclaration.style.setProperty accepts css/hyphen type property names without conversion, as documented here

Try this hyphenated property, for example:

document.body.style.setProperty("background-color", "red");

You can also do this:

document.body.style["background-color"] = "silver";

These approaches - if you can use them - may be simpler.

Upvotes: 2

jahu
jahu

Reputation: 5657

I was about to ask question about the same thing (and I intended to name it "Translate css names to\from javascript counterparts"). Somehow I ended up writing my own solution.

function cssNameToJsName(name)
{
    var split = name.split("-");
    var output = "";
    for(var i = 0; i < split.length; i++)
    {
        if (i > 0 && split[i].length > 0 && !(i == 1 && split[i] == "ms"))
        {
            split[i] = split[i].substr(0, 1).toUpperCase() + split[i].substr(1);
        }
        output += split[i];
    }
    return output;
}

function jsNameToCssName(name)
{
    return name.replace(/([A-Z])/g, "-$1").toLowerCase();
}

Upvotes: 2

rodneyrehm
rodneyrehm

Reputation: 13557

So you're basically reinventing jQuery.css(). Maybe a look at how jQuery solved the camelCase problem might help: https://github.com/jquery/jquery/blob/master/src/core.js#L600

Upvotes: 7

Related Questions