Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the css class rules using jQuery?

Tags:

jquery

css

Can any one help me please, I have two sections of my question.

  1. What I want to do is changing css class rules using jQuery on the fly.

    .classname{color:red; font-size:14px;}

    In example above I have a class named .classname now using jQuery I want to change the font size only not color with in .classname not by adding css inline.

  2. I want to create and save .classname change to a file remember there will be complete stylesheet or no of classnames that will be save in file.

How I can do this the easiest and better way?

Thanks!

like image 455
Yasir Avatar asked Mar 07 '09 16:03

Yasir


People also ask

Can we change CSS using jQuery?

You can change CSS using the jQuery css() method which is used for the purpose of getting or setting style properties of an element. Using this method you can apply multiple styles to an HTML all at once by manipulating CSS style properties.

Can you access a CSS class from jQuery?

jQuery provides toggleClass() method to toggle an CSS class on the matched HTML element(s). Following is the syntax of the toggleClass() method: $(selector).

Can you change a CSS class with JavaScript?

With JavaScript, we are able to set CSS styles for one or multiple elements in the DOM, modify them, remove them or even change the whole stylesheet for all your page.

Can we change CSS properties value using JavaScript and jQuery?

css('opacity', '0.2'); Finally, setting multiple css properties with jQuery can be done by passing in a javascript object. The key is name of the css property, and the value will be the css value.


4 Answers

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

like image 78
Ionuț G. Stan Avatar answered Oct 16 '22 06:10

Ionuț G. Stan


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");
like image 24
Nilesh Avatar answered Oct 16 '22 08:10

Nilesh


You should take this approach only if:

  • You need to set the value to something that is impractical to enumerate (i.e. varying width in pixels) with class names
  • And you want to apply this style to elements that will be inserted in the DOM in the future

There is a jQuery plugin that does that: http://plugins.jquery.com/project/jquerycssrule

For a small project I worked on I extracted the bare essentials and created the following function:

function addCSSRule(sel, prop, val) {
    for(var i = 0; i < document.styleSheets.length; i++){
        var ss    = document.styleSheets[i];
        var rules = (ss.cssRules || ss.rules);
        var lsel  = sel.toLowerCase();

        for(var i2 = 0, len = rules.length; i2 < len; i2++){
            if(rules[i2].selectorText && (rules[i2].selectorText.toLowerCase() == lsel)){
                if(val != null){
                    rules[i2].style[prop] = val;
                    return;
                }
                else{
                    if(ss.deleteRule){
                        ss.deleteRule(i2);
                    }
                    else if(ss.removeRule){
                        ss.removeRule(i2);
                    }
                    else{
                        rules[i2].style.cssText = '';
                    }
                }
            }
        }
    }

    var ss = document.styleSheets[0] || {};
    if(ss.insertRule) {
        var rules = (ss.cssRules || ss.rules);
        ss.insertRule(sel + '{ ' + prop + ':' + val + '; }', rules.length);
    }
    else if(ss.addRule){
        ss.addRule(sel, prop + ':' + val + ';', 0);
    }
}
like image 13
Blago Avatar answered Oct 16 '22 07:10

Blago


If I understand your question correctly, you would like to read through a CSS file, make changes to a class and then persist those changes by saving the file?

You can't do this with JavaScript/jQuery running from the client side; You can certainly change the font size of each individual element in the DOM that matches the CSS class .classname, like so

$('.classname').css('font-size','14px');

but client-side JavaScript cannot access the filesystem from the web browser, so you would need some other way (i.e. server-side code) to make changes to the CSS file itself.

like image 12
Russ Cam Avatar answered Oct 16 '22 06:10

Russ Cam