I believe the .addClass() function in jQuery attaches a CSS class to the current selection, but I was wondering I could create or define a CSS class in jQuery, and then attach it?
jQuery Manipulating CSSaddClass() - Adds one or more classes to the selected elements. removeClass() - Removes one or more classes from the selected elements. toggleClass() - Toggles between adding/removing classes from the selected elements. css() - Sets or returns the style attribute.
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.
If you want to use a class, use a full stop (.) followed by the class name in a style block. Next, use a bracket called a declaration block that contains the property to stylize the element, such as text color or text size. CSS Classes will help you stylize HTML elements quickly.
The jQuery CSS methods allow you to manipulate CSS class or style properties of DOM elements. Use the selector to get the reference of an element(s) and then call jQuery css methods to edit it. Important DOM manipulation methods: css(), addClass(), hasClass(), removeClass(), toggleClass() etc.
Actually, you can create a CSS rule that will affect all elements on the current page. In most browsers it should be as simple as:
var style = $('<style>body { background: green; }</style>') $('html > head').append(style);
This may or may not work in IE, however you can use IE's proprietary addRule instead:
document.styleSheets[0].addRule('body', 'background: green', -1);
Naturally this will not assist you in creating css files that can be shared between webpages, but it is a handy way of affecting the style of a large number of elements without the need to iterate over them.
I'm not exactly sure what you want, but I think the best you can do is something like this:
var someClass = { "width": "100%", "background": "#ffffff" }; $(this).css(someClass);
Note that this is not actually creating a class, but it might do what you need.
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