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


HTML



Edit in JSFiddle

 
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


HTML



Edit in JSFiddle

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


HTML



Edit in JSFiddle

 
If you prefer to directly use the CSS properties names instead of their JavaScript equivalent, you can do like:

JS


HTML



Edit in JSFiddle

3. Using JavaScript – setProperty() method

Alternatively, you can use the setProperty() method to set a new value for a CSS property.

JS


HTML



Edit in JSFiddle

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


HTML



Edit in JSFiddle

That’s all about adding a CSS property to an element using JavaScript and Query.