Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define multiple CSS attributes in jQuery?

Tags:

jquery

css

Is there any syntactical way in jQuery to define multiple CSS attributes without stringing everything out to the right like this:

$("#message").css("width", "550px").css("height", "300px").css("font-size", "8pt"); 

If you have, say, 20 of these your code will become hard to read, any solutions?

From jQuery API, for example, jQuery understands and returns the correct value for both

.css({ "background-color": "#ffe", "border-left": "5px solid #ccc" })  

and

.css({backgroundColor: "#ffe", borderLeft: "5px solid #ccc" }). 

Notice that with the DOM notation, quotation marks around the property names are optional, but with CSS notation they're required due to the hyphen in the name.

like image 810
Edward Tanguay Avatar asked Jan 15 '09 15:01

Edward Tanguay


People also ask

How can use multiple CSS properties in jQuery?

Apply multiple CSS properties using a single JQuery method CSS( {key1:val1, key2:val2....). You can apply as many properties as you like in a single call. Here you can pass key as property and val as its value as described above.

How do you add multiple CSS?

The DOM style property is the simplest way to set and get CSS styles from an element in JavaScript. Usually, when you want to add multiple CSS properties to an element, you have to set them individually as shown below: const btn = document. querySelector('.

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.

Can we change CSS properties values using JavaScript or 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.


2 Answers

Better to just use .addClass() and .removeClass() even if you have 1 or more styles to change. It's more maintainable and readable.

If you really have the urge to do multiple CSS properties, then use the following:

.css({    'font-size' : '10px',    'width' : '30px',    'height' : '10px' }); 

NB!
Any CSS properties with a hyphen need to be quoted.
I've placed the quotes so no one will need to clarify that, and the code will be 100% functional.

like image 168
redsquare Avatar answered Sep 23 '22 13:09

redsquare


Pass it as an Object:

$(....).css({     'property': 'value',      'property': 'value' }); 

http://docs.jquery.com/CSS/css#properties

like image 25
dave mankoff Avatar answered Sep 21 '22 13:09

dave mankoff