Skip to content
Related Articles

Related Articles

Improve Article

How to apply CSS style using jQuery ?

  • Last Updated : 20 Sep, 2021
Geek Week

In this article, we will explore how we can apply CSS styles to HTML elements. It is recommended that you have some basic knowledge of HTML, CSS, JavaScript, and jQuery before beginning this article.

It is possible to change the CSS property of an element by using a simple JavaScript API, but we try to complete this challenge using jQuery css() method.  

Syntax:

$().css(propertyname, value);
$().css(properties);

There are many types of CSS methods, which means that each method has the same name but takes different parameters. We will discuss only two methods, one of which is used to change a single CSS property, while the other is used to change multiple CSS properties simultaneously. With the second method, you can pass a JSON string object as a parameter that you want to apply to the HTML element. 

JSON string objects contain CSS properties along with their values, and the first method only takes 2 parameters, namely the property name and the value.



Example: By clicking the button, it adds multiple CSS properties to the selected element, but by double-clicking the button, it adds only one CSS property. The motive of this example is to show the use of two types of CSS methods which are discussed. 

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
</head>
  
<body style="text-align: center; 
    border: 2px solid green;
    min-height: 240px;">
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
  
    <p id="context">
        Hello Geeks!! welcome to geeksforgeeks
    </p>
  
    <br>
  
    <button id="change">
        clickme
    </button>
  
    <script>
        let css_property =
        {
            "color": "green",
            "font-size": "20px"
        }
        $('#change').on('click', function () {
  
            // For multiple css property
            $('#context').css(css_property);
        });
  
        $('#change').on('dblclick', function () {
              
            // For single css property
            $('#context').css('display', 'none');
        })
    </script>
</body>
  
</html>

Output:

output

Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :