Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a CSS class in jQuery

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?

like image 368
Qcom Avatar asked Aug 03 '10 02:08

Qcom


People also ask

How we can add CSS with jQuery?

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.

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.

How do I add a class in CSS?

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.

Can jQuery manipulate CSS?

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.


2 Answers

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.

like image 102
MooGoo Avatar answered Oct 06 '22 01:10

MooGoo


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.

like image 30
Stephen Watkins Avatar answered Oct 06 '22 01:10

Stephen Watkins