Can I fetch the value of a non-standard CSS property via Javascript?

Modern browsers will just throw away any invalid css. However, you can use the content property since it only has effect with
:after, :before etc. You can store JSON inside it:

#someElement {
    content: '{"foo": "bar"}';
}

Then use code like this to retrieve it:

var CSSMetaData = function() {

    function trimQuotes( str ) {
         return str.replace( /^['"]/, "" ).replace( /["']$/, "" );   
    }

    function fixFirefoxEscape( str ) {
        return str.replace( /\\"/g, '"' );
    }

    var forEach = [].forEach,
        div = document.createElement("div"),
        matchesSelector = div.webkitMatchesSelector ||
                          div.mozMatchesSelector ||
                          div.msMatchesSelector ||
                          div.oMatchesSelector ||
                          div.matchesSelector,
        data = {};

    forEach.call( document.styleSheets, function( styleSheet ) {
        forEach.call( styleSheet.cssRules, function( rule ) {
            var content = rule.style.getPropertyValue( "content" ),
                obj;

            if( content ) {
                content = trimQuotes(content);
                try {
                   obj = JSON.parse( content );
                }
                catch(e) {
                    try {

                        obj = JSON.parse( fixFirefoxEscape( content ) );
                    }
                    catch(e2) {
                        return ;
                    }

                }
                data[rule.selectorText] = obj;
            }
        });

    });


    return {

        getDataByElement: function( elem ) {
            var storedData;
            for( var selector in data ) {
                if( matchesSelector.call( elem, selector ) ) {
                    storedData = data[selector];
                    if( storedData ) return storedData;

                }
            }

            return null;
        }
    };

}();
var obj = CSSMetaData.getDataByElement( document.getElementById("someElement"));
console.log( obj.foo ); //bar

Note, this is only for modern browsers. Demo: http://jsfiddle.net/xFjZp/3/

Leave a Comment