7

From this code:

HTML

<div class="test"></div>

CSS

.test {
    background-color:red;
    font-size:20px;
    -custom-data1: value 1;
    -custom-data2: 150;
    -custom-css-information: "lorem ipsum";

}

With javascript -- for example from a $('.test') -- how can I get a list of the CSS attributes wich have the property name starting with the prefix "-custom-" ? (they can have various name, but always the same prefix)

I would like to get this:

{
    customData1: "value 1",
    customData2: 150,
    customCssInformation: "lorem ipsum"
}

I know that I can also use the data- HTML attribute, but for some very specifics reasons I need to use a CSS equivalent. Thanks for your help.

4
  • 2
    You might want to check out this question: stackoverflow.com/questions/2926326/… Commented Aug 31, 2011 at 2:03
  • 1
    You should consider using data-* attributes for this. Commented Aug 31, 2011 at 2:03
  • @Andrew: yes I know, but for a very specific reason, i need to use in my css an equivalent of the data- HTML attribute. Commented Aug 31, 2011 at 2:13
  • note that any solution will involve the parsing of text, as far as the browser is concerned, the CSS is simply large text strings. So, if you have gigantic css files, keep in mind potential performance issues. Commented Aug 31, 2011 at 3:23

3 Answers 3

3

Short Answer: IE 9 will give you these values.

However, Firefox/Chrome/Safari parse them out.

example jsfiddle

you can loop through the document's stylesheets to find a match to the desired selector (note that this can be a costly procedure especially on sites with large/multiple CSS files)

var css = document.styleSheets, 
    rules;

// loop through each stylesheet
for (var i in css) {
    if (typeof css[i] === "object" && css[i].rules || css[i].cssRules) {
        rules = css[i].rules || css[i].cssRules;
        // loop through each rule
        for (var j in rules) {
            if (typeof rules[j] === "object") {
                if (rules[j].selectorText) {
                    // see if the rule's selectorText matches
                    if (rules[j].selectorText.indexOf('.test') > -1) {
                        // do something with the results.
                        console.log(rules[j].cssText);
                        $('.test').html(rules[j].cssText);
                    }
                }
            }
        }
    }
}

you'll notice in browsers other than IE 9 (haven't tested IE 8 or lower) that the -custom- styles have been removed from the cssText.

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

Comments

1

Here's a solution that can get the custom css attributes:

<style>
.custom-thing
{
    -custom-1: one;
    -custom-2: 4;
}
</style>
<a class='custom-thing' href='#' onclick='test();'>test</a>
<script>
    function test() {
        var valueOne = getCssValue('.custom-thing', '-custom-1');
        alert(valueOne);

        var valueTwo = getCssValue('.custom-thing', '-custom-2');
        alert(valueTwo);
    }

    function getCssValue(selector, attribute) {
        var raw = getRawCss(selector);
        if (!raw) {
            return null;
        }
        var parts = raw.split(';');
        for (var i in parts) {
            var subparts = parts[i].split(':');
            if (trimString(subparts[0]) == attribute) {
                return subparts[1];
            }
        }
        return null;
    }

    function trimString(s) {
        return s.replace(/^\s+|\s+$/g, ""); 
    }

    function getRawCss(selector) {
        for (var i = 0; i < document.styleSheets.length; i++) {
            var css = document.styleSheets[i].rules || document.styleSheets[i].cssRules;
            for (var x = 0; x < css.length; x++) {
                if (css[x].selectorText == selector) {
                    return (css[x].cssText) ? css[x].cssText : css[x].style.cssText;
                }
            }
        }
        return null;
    }
</script>

This took me a little bit to put together, and I never knew you could do this before.

Pretty Cool!

2 Comments

Thank you for your answer, I tested it but it look like to run only on IE (IE9), and just with the -custom-2 attribute. With other browsers it always return me null.
This doesn't appear to work in Chrome when the stylesheet is loaded externally; only the properties that are used are queryable
0

Rather late, but I believe it's worth the fuss posting it, in case I can help others too.

var css = document.styleSheets[0]; // some stylesheet

var result = [];
for (var r=0; r<css.rules.length; r++)
{
   var item = { selector: css.rules[r].selectorText };
   var styles = {};
   for (var s in css.rules[r].style)
   {
       if (!isNaN(s))
       {
            var key = css.rules[r].style[s];
            var val = css.rules[r].style[key];
            styles[key] = val;
       }
   }
   item.styles = styles;
   result.push(item);
}

console.log(result);

And it will print you out a neat tree with all the selectors and their properties. :)

Comments

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.