Define multiple CSS attributes using JavaScript/jQuery
This post will discuss how to define multiple CSS attributes using JavaScript and jQuery.
1. Using JavaScript
In JavaScript, you can target the style attribute of an element to apply multiple styles in a single statement. This can be easily done using the Object.assign() method, which can merge the specified styles with the existing styles in the style attribute.
JS
|
1 2 3 4 5 6 7 8 |
var styles = { "background-color": "lightgray", "width": "500px", "height": "300px" }; var obj = document.getElementById("container"); Object.assign(obj.style, styles); |
HTML
|
1 |
<div id="container"></div> |
Another plausible way is to use the setAttribute() method for setting the value of style attribute on the specified element. This has the advantage that you can apply multiple styles for an element in a single declaration, but it risks overriding the existing styles already applied to the style attribute.
JS
|
1 2 |
var obj = document.getElementById("container"); obj.setAttribute("style", "width: 500px; height: 300px; background-color: lightgray;"); |
HTML
|
1 |
<div id="container"></div> |
You can also use the setProperty() method or the style property to set CSS properties on an element, but these have the major disadvantage that multiple CSS properties have to be individually set one at a time.
2. Using jQuery
With jQuery, you can use the .css() method for setting multiple CSS properties on an element. You can specify the property name and its value as separate parameters to the .css() method.
JS
|
1 2 3 4 5 |
$(document).ready(function() { $("#container").css("background-color", "lightgray") .css("width", "500px") .css("height", "300px"); }); |
HTML
|
1 |
<div id="container"></div> |
To define multiple CSS attributes in a single statement, you can pass a single object of key-value pairs to the .css() method, as shown below:
JS
|
1 2 3 4 5 6 7 |
$(document).ready(function() { $("#container").css({ "background-color": "lightgray", "width": "500px", "height": "300px" }); }); |
HTML
|
1 |
<div id="container"></div> |
That’s all about setting multiple CSS properties using JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)