Open In App

How to Define Multiple CSS Attributes in jQuery ?

In jQuery, you can define multiple CSS attributes for an element using the css() method. This method allows you to set one or more CSS  properties for an element. In this article, we will see the different ways to define multiple CSS attributes in jQuery.

Syntax: The syntax for defining multiple CSS attributes using the jQuery css() method.



$(selector).css({
     propertyName1 : value1,
     propertyName2 : value2,
     ...
     propertyNameN : valueN,
});

Where,

 Approaches: There are two approaches to defining multiple CSS attributes in jQuery.



Example 1: In this example, we are using an object literal to define multiple CSS attributes, i.e., we are using an object literal to define the ‘color’, ‘background-color’, and ‘font-size’ CSS attributes for the element with the ID ‘myElement’.




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
</head>
  
<body style='text-align:center'>
    <h1 style='color:green'>
        Geeksforgeeks
    </h1>
  
    <h2 id='myElement'>
        Define multiple CSS attributes
    </h2>
  
    <script>
        $('#myElement').css({
            'color' : 'red',
            'background-color' : 'yellow',
            'font-size' : '24px'
        });
    </script>
</body>
  
</html>

Output:

 

Example 2: in this example, we are using individual arguments to define multiple CSS attributes, i.e., we are using individual arguments to define the ‘color ‘, ‘background-color’, and ‘ font-size’ CSS attributes for the element with the ID ‘myElement ‘. We are chaining the css() method to apply each attribute separately.




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
</head>
  
<body style='text-align:center'>
    <h1 style='color:green'>
        Geeksforgeeks
    </h1>
  
    <h2 id='myElement'>
        Define multiple CSS attributes
    </h2>
  
    <script>
        $('#myElement').css('color' , 'red')
        .css('background-color' , 'yellow')
        .css('font-size' , '24px');
    </script>
</body>
  
</html>

Output:

 


Article Tags :