The beauty of JQuery is that it provides some readily available methods that helps us deal with CSS easily.
Say, you have a <p> element and on button click you want to change the color of the <p> element to red and increase its font size to 50px.
And we know that we can achieve it using CSS using the style property,
{"color": "red", "font-size": "50px"}
And luckily, JQuery provides a method called css(). You can pass the above style property to the css() method and it works as expected.
Let us see in the below example,
<html> <head> <title> My First Programme </title> </head> <body> <h1> JQuery </h1> <p>New Code</p> <button> Click Here </button> <script src = "https://cdnjs.cloudflare.com/ajax/libs/JQUERY/3.3.1/jquery.min.js"> </script> <script> $('button').click( function() { $('p').css({"color": "red", "font-size": "50px"}); }); </script> </body> </html>
So, on button click, the below JQuery statement gets executed,
$('button').click( function() { $('p').css({"color": "red", "font-size": "50px"}); });
And the content of the <p> element gets changed with color, red and font size 50px.
Just remember any css property can be passed as is to the css() method and it acts accordingly.
Say in the above case, the css style property is, {"color": "red", "font-size": "50px"} and we pass it as is to the css() method.
Also the css() method acts as a getter method.
Say, you want to get the color of a <p> element.
Let us see with the below example,
<html> <head> <title> My First Programme </title> </head> <body> <h1> JQuery </h1> <p style = "color: red">New Code</p> <button> Click Here </button> <script src = "https://cdnjs.cloudflare.com/ajax/libs/JQUERY/3.3.1/jquery.min.js"> </script> <script> $('button').click( function() { alert("The color of the <p> is : "+$('p').css("color")) }); </script> </body> </html>
So, if you look at the above output (i.e. The alert), it says,
The color of the <p> is : rgb(255, 0, 0)
rgb(255, 0, 0) is the red color.
So, we get the color of the <p> element i.e. red.
This is because of the css() method(i.e. $(p).css("color")).
alert("The color of the <p> is : "+$(p).css("color"))
That is used to get the color of the <p> element.
There are also some other methods that helps us work with CSS effectively. Below is the list :