How to change CSS of an element using jQuery
jQuery is a JavaScript library that provides us with multiple features and tools to handle the HTML document. It is widely used as it is faster and more efficient in performing web development-related tasks, including object animations and event handling.
To use jQuery, we must include its library in the HTML document. To include the library, write the following code:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
In this Answer, we will change the CSS of the elements in the HTML document using jQuery's css() method.
The css() method
We use the css() method to change the CSS of the elements. Since this method is part of JavaScript, we should have to write it under the <script> tag in the HTML code.
Syntax
The syntax of css() method is as follows:
$(selector).css(propertyName, value);
$(selector): This is the element we want to change the CSS of.propertyName: This is the CSS property we want to set.value: This is the new value we set for the CSS property. It can have any variable type depending on the CSS property's requirement.
Examples
The following examples will help us clear our understanding of the css() method:
For a single CSS property
We use the css() method in the following code example to set CSS for a single property.
Let's understand what happens in our code:
Lines 3–5: We define the document's
titlein the<head>tag.Lines 8–12: We write the JavaScript code in the
<script>tag. Thedocument.ready()function executes after the DOM has loaded completely without making an explicit call. In this function, we change the CSS of the<h1>tag using thecss()method. We change the value ofcolorproperty of<h1>tag toblue.Lines 14–16: We create a heading element in the
<body>tag.
For multiple CSS properties
To set multiple CSS properties, we can either use the css() method several times or call it once.
The following code example calls the css() method multiple times to set the different CSS properties of an element:
Let's understand what happens in the script code:
Lines 8–13: In this function, we use the
css()method twice to change two CSS properties of the<h1>tag. First, we change the property ofcolortoblue, then we change thetext-decorationtounderline.
The following code example calls the css() method only once:
Let's understand what happens in the script code:
Line 8–15: In this function, we use the
css()method to change the CSS of two properties of the<h1>tag. We change the property ofcolortoblueandtext-decorationtounderline.
Conclusion
Changing the CSS of an element using jQuery is a simple and easy process. Using the css() method, we can change a variety of CSS properties of chosen components.
Free Resources