How jQuery Add Style to HTML Element and Apply CSS

There are methods jQuery css() and jQuery attr() by which jquery add style to HTML elements. There are many CSS properties you can set to the HTML element using these methods. You can add single as well as multiple CSS properties using jQuery methods here.

Let’s start learning these methods below here.

How jQuery Add Style to HTML Element Using css()

jQuery add style to the HTML element using css() method. There are two parameters you have to use with this method. The first parameter requires the jQuery selector to specify the id or class of the HTML element and access the element. The second parameter requires property name with its value.

See jQuery css() method to look for syntax.

Add Single Style

Output


Click the above button to add single style to HTML element using jQuery CSS method.

The above example adds the color property as red its value to the HTML paragraph element using its id. Click the “Add single Style” button to view the changes made by the CSS method.

Bonus: download a Free jQuery cheat sheet that will show you 20+ most important examples to learn in jQuery.

Add Multiple Style

Output


Click the above button to add multiple style CSS to HTML element using jQuery CSS method.

The above example add multiple CSS properties to the paragraph element by using the css() and element id. You have to specify the multiple CSS properties inside the curly bracket within the css().

note: jQuery css() is not the method to add attributes. But if the HTML element does not have style attribute, css() adds the style attribute and then after adding the CSS properties inside the style attribute.

Apply CSS to HTML Element Using jQuery attr()

jQuery attr() method is used to add attributes to HTML elements. However, you can use this method to apply CSS with added attributes and CSS properties to HTML elements.

See jQuery attr() method to learn the syntax and see below example for adding attribute using attr().

Add Single Style

Output


Click the above button to add a style attribute to HTML element using jQuery attr() method.

The above example adds a color property to HTML element with red as its value by accessing the element using its id. The method first adds the style attribute to the HTML element then after it adds the CSS property to its values.

Add Multiple Style

Output


Click the above button to add multiple style CSS to HTML element using jQuery attr() method.

The above example adds multiple CSS properties using the attr() method. You can specify the comma(,) separated CSS properties with its value inside the attr() method.

DOWNLOAD Free jQuery CHEAT SHEET

You May Also Like to Read