views:

256

answers:

5

I believe the .addClass() function in jQuery attaches a CSS class to the current selection, but I was wondering I could create or define a CSS class in jQuery, and then attach it?

+5  A: 

I'm not exactly sure what you want, but I think the best you can do is something like this:

var someClass = { "width": "100%", "background": "#ffffff" };
$(this).css(someClass);

Note that this is not actually creating a class, but it might do what you need.

stjowa
OK thanks, I know what you mean.
BOSS
Note that class is a reserved word in JavaScript
gregers
+3  A: 

you can not create or define a CSS class in jQuery. But with .css() you could do something like this,

var $square = {
       display: 'block',
       width: '50px',
       height: '100px'
    }

$('.elem0, .elem1, .elem2, .elem3').css($square);
Reigel
Be careful about not including quotes around the name. According to jQuery's documentation: "...with the DOM notation, quotation marks around the property names are optional, but with CSS notation they're required due to the hyphen in the name."
stjowa
@stjowa Yeah! But also, including quotes can be expensive. I forgot where I read an article about that though ;)
Reigel
+14  A: 

Actually, you can create a CSS rule that will affect all elements on the current page. In most browsers it should be as simple as:

var style = $('<style>body { background: green; }</style>')
$('html > head').append(style);

This may or may not work in IE, however you can use IE's proprietary addRule instead:

document.styleSheets[0].addRule('body', 'background: green', -1);

Naturally this will not assit you in creating css files that can be shared between webpages, but it is a handy way of affecting the style of a large number of elements without the need to iterate over them.

MooGoo
+5  A: 

Here's something that will create a CSS class that will be available everywhere and apply it to a jQuery object. This uses the same basic technique as mentioned by MooGoo but is fleshed out into a fully functional piece of code:

(function() {
    var addRule;

    if (typeof document.styleSheets != "undefined" && document.styleSheets) {
        addRule = function(selector, rule) {
            var styleSheets = document.styleSheets, styleSheet;
            if (styleSheets && styleSheets.length) {
                styleSheet = styleSheets[styleSheets.length - 1];
                if (styleSheet.addRule) {
                    styleSheet.addRule(selector, rule)
                } else if (typeof styleSheet.cssText == "string") {
                    styleSheet.cssText = selector + " {" + rule + "}";
                } else if (styleSheet.insertRule && styleSheet.cssRules) {
                    styleSheet.insertRule(selector + " {" + rule + "}", styleSheet.cssRules.length);
                }
            }
        }
    } else {
        addRule = function(selector, rule, el, doc) {
            el.appendChild(doc.createTextNode(selector + " {" + rule + "}"));
        };
    }

    var createCssClass = function(className, cssProps, doc) {
        doc = doc || document;

        var head = doc.getElementsByTagName("head")[0];
        if (head && addRule) {
            var selector = "*." + className;
            var ruleBits = [];
            for (var i in cssProps) {
                if (cssProps.hasOwnProperty(i)) {
                    ruleBits.push(i + ":" + cssProps[i] + ";");
                }
            }
            var rule = ruleBits.join("");
            var styleEl = doc.createElement("style");
            styleEl.type = "text/css";
            styleEl.media = "screen";
            head.appendChild(styleEl);
            addRule(selector, rule, styleEl, doc);
            styleEl = null;
        }
    };

    jQuery.fn.createAndApplyCssClass = function(className, cssProps) {
        createCssClass(className, cssProps, document);
        this.addClass(className);
    };
})();

$("#someelement").createAndApplyCssClass("test", {
    "background-color": "green",
    "color" : "white"
});
Tim Down
+1  A: 

With jQuery.Rule you can write code like this to append a new CSS rule:

$.rule('#content ul{ border:1px solid green }').appendTo('style');

Extending a rule:

$.rule('#content ul', 'style').append('background:#FF9');

Removing the whole rule:

$.rule('#content ul', 'style').remove();

There is more in the API docs.

Internally, it uses the "append stylesheet to head" trick that MooGoo mentioned as well.

andras