Add a CSS property to an element with JavaScript/jQuery
This post will discuss how to apply a CSS property to an element using JavaScript and jQuery.
There are several ways to apply a CSS property to an element using JavaScript and jQuery. All these alternatives directly or indirectly target the style global attribute, which contains the CSS styling declarations for the element.
1. Using jQuery – .css() method
In jQuery, you can use the .css() method for setting one or more CSS properties on an element. It works by modifying the value of the style property of the element.
JS
|
1 2 3 |
$(document).ready(function() { $("#container").css("background-color", "lightgray"); }); |
HTML
|
1 |
<div id="container" class="main"></div> |
The above version of the .css() method takes the property name and value as separate parameters. To add multiple CSS attributes in a single line, 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" class="main"></div> |
2. Using JavaScript – style property
In pure JavaScript, you can use the style property to inline set the style of an element. Please refer to this article to get the list of JavaScript equivalents of common CSS properties.
JS
|
1 2 |
var obj = document.getElementById("container"); obj.style.backgroundColor = "lightgray"; |
HTML
|
1 |
<div id="container" class="main"></div> |
If you prefer to directly use the CSS properties names instead of their JavaScript equivalent, you can do like:
JS
|
1 2 |
var obj = document.getElementById("container"); obj.style["background-color"] = "lightgray"; |
HTML
|
1 |
<div id="container" class="main"></div> |
3. Using JavaScript – setProperty() method
Alternatively, you can use the setProperty() method to set a new value for a CSS property.
JS
|
1 2 |
var obj = document.getElementById("container"); obj.style.setProperty("background-color", "lightgray"); |
HTML
|
1 |
<div id="container" class="main"></div> |
4. Using JavaScript – setAttribute() method
Another plausible way is to use the setAttribute() method for setting the value of the style attribute on the specified element. This has the advantage that you can apply multiple styles in a single declaration, but risks overriding the existing styles applied to the style attribute.
JS
|
1 2 |
var obj = document.getElementById("container"); obj.setAttribute("style", "background-color: lightgray; width: 500px; height: 300px;"); |
HTML
|
1 |
<div id="container"></div> |
That’s all about adding a CSS property to an element using JavaScript and Query.
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 :)