Is it in any way possible, to change a css class model using JavaScript?

Pseudo code:

function updateClass(className, newData) {
    cssInterface.alterClass(className, newData);
}

className being the name of the class, which is supposed to be changed (like ".footer") and newData being the new class content (like border: "1px solid pink;").

The target is, actually, just to save space: I am working with CSS3-animations, so changing one attribute of an element, which is affected by it's class, will terminate the animation of of it - The (in my case) font size won't change anymore. Using different classes will require an entire new set of classes for all affected elements, I'd like to avoid this.

I am not searching for a change via

element.className = "foo";

or

element.style.fontSize = "15pt";

Thanks for your help, guys :)

share|improve this question
What about jquery ? – Sheikh Heera Mar 22 '12 at 22:04
Yes if you know which stylesheet the rule is in (well you could just iterate over all of them I guess) and that stylesheet is hosted by sameDomain – Esailija Mar 22 '12 at 22:09

3 Answers

up vote 0 down vote accepted

See my answer here. To answer your question: Yes, it's possible.

@CSS3: I tried exactly the same in one of my html5 experiments. I created an extra <style> element, and changed its contentText to the CSS class definitions I needed. Of course changing the cssRule object would be much cleaner :-)

share|improve this answer
it's actually the innerText-attribute of the style-element (which, to complete the answer can be accessed using an id or whatever), but it worked - thanks a lot! – brickBreaker Mar 23 '12 at 22:26
Right, that attribute seems to be browser-dependent. IE seems to need styleSheets.cssText, others are lucky with TextNodes. Haven't tried innerHTML/innerText yet. – Bergi Mar 27 '12 at 17:41
there is only one thing to say about internet explorer: 9gag i guess, innerHTML wouldn't work - after all it's css. – brickBreaker Mar 28 '12 at 20:35

As far as I can tell the CSS object model cannot easily tell you whether you already have an existing style rule for a particular class, but you can easily append a new rule for that class and it will override any previous declaration of that style.

I found an example of creating dynamic stylesheets.

share|improve this answer

You should take a look at dojo, it has some nice features where you can do just that..

require(["dojo/dom-class"], function(domClass){
    // Add a class to some node:
    domClass.add("someNode", "anewClass");
});

http://dojotoolkit.org/reference-guide/1.7/dojo/addClass.html

share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.