Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change CSS rule in class using JQuery

I have a class in CSS

.Foo {   width:20px; } 

Using Jquery I would like to do something similar to this on an event:

$(".Foo").css("width", "40px"); 

This doesn't work. Is this the wrong approach? Should I use addClass() and removeClass()?

EDIT: I figured out my problem. This command does in fact work. In my particular application I hadn't created the elements using the class before I used the command, so when they were created nothing was changed.

Basically this command doesn't change the CSS style rule, just the elements using the class.

like image 603
jdw Avatar asked May 24 '11 18:05

jdw


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 we change CSS properties values using Javascript or jQuery?

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.

What is the use of CSS () method in jQuery?

jQuery css() Method The css() method sets or returns one or more style properties for the selected elements. When used to return properties: This method returns the specified CSS property value of the FIRST matched element.


1 Answers

You can change a CSS style rule. You need to look at:

document.styleSheets collection
styleSheet.cssRules property (or styleSheet.rules for IE7 and IE8)
rule.selectorText property
rule.style property

For example:

var ss = document.styleSheets[0]; var rules = ss.cssRules || ss.rules; var fooRule = null; for (var i = 0; i < rules.length; i++) {     var rule = rules[i];     if (/(^|,) *\.Foo *(,|$)/.test(rule.selectorText))     {         fooRule = rule;         break;     } } fooRule.style.width = "40px"; 

Working demo: jsfiddle.net/kdp5V

like image 141
gilly3 Avatar answered Sep 16 '22 14:09

gilly3