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.
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.
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.
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.
You can change a CSS style rule. You need to look at:
document.styleSheets
collectionstyleSheet.cssRules
property (or styleSheet.rules
for IE7 and IE8)rule.selectorText
propertyrule.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With