How can I change the css class rules using jQuery?

Solution 1:

As far as I know there's no jQuery way to do this. There might be some jQuery plugin for this but I don't know.

Basically, what you're trying to achieve in your first question is possible using the styleSheets property of the document object. It's a little bit more complicated than that as you need to walk to a rather deep object chain, but nevertheless works in all major browsers including Internet Explorer 6. Below is a proof of concept. The CSS is inside a STYLE tag, but works with external CSS just as well. I'll let you do the abstractions.

Proof of Concept

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html>
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta http-equiv="imagetoolbar" content="false">
<meta http-equiv="imagetoolbar" content="no">
<style type="text/css">
.classname {
 color: red;
 font-size: 14px;
}
</style>
<script type="text/javascript">
window.onload = function() {
    document.getElementById("button").onclick = function() {
        var ss = document.styleSheets;

        for (var i=0; i<ss.length; i++) {
            var rules = ss[i].cssRules || ss[i].rules;

            for (var j=0; j<rules.length; j++) {
                if (rules[j].selectorText === ".classname") {
                    rules[j].style.color = "green";
                }
            }
        }
    };
}
</script>
</head>
<body>

<h1 class="classname">Some red text</h1>

<button id="button">Make text green</button>

</body>
</html>

For your second question, I don't have time to write a solution but it would involve reading the CSS declarations just as above and use the cssText property of a CssRule object in order to build a string which will eventually be sent to the server using a Ajax POST request. The server side is your business.

References:

  • document.styleSheets (Mozilla)
  • styleSheet object (Mozilla)
  • CssRule object (Mozilla)
  • document.styleSheets (MSDN)
  • CssRule object (MSDN)

Hope it helps

Solution 2:

Recently I had the need to fix some jquery theme issue for Autocomplete widget. I wanted to change the background color of the autocomplete widget.

So I looked up the CSS and found that the autocomplete class is defined like this

.ui-autocomplete { position: absolute; cursor: default; }   

So in my program I issue the following statement to change the class by adding the background property. Note that I keep the other attributes as it is otherwise it will break existing functionality

$("<style type='text/css'> .ui-autocomplete { position: absolute; cursor: default; background:black; color:white} </style>").appendTo("head");