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.
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.
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('.
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 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.
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.
Pass it as an Object:
$(....).css({ 'property': 'value', 'property': 'value' });
http://docs.jquery.com/CSS/css#properties
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