How to apply multiple CSS properties using jQuery?

Apply multiple CSS properties using jQuery CSS( {key1:val1, key2:val2....}) method. We can apply as many properties as we like in a single call.

Syntax

In the below mentioned way we can use the CSS. Here you can pass key as property and val as its value of that property.

selector.css( {key1:val1, key2:val2....keyN:valN})

Define Multiple CSS Attributes in jQuery

As we mentioned earlier that we will be using jQuery css() method to apply multpile CSS properties on any element.

  • First we will use '$(selector)' to select the element where we wants to apply our CSS properties.
  • Then we will add CSS properties one by one in the 'key: value'; format. We can use CSS porperties as an object literal or as an indivitual argument, as we want.

Ways to Define CSS Property in jQuery

There are two ways to include CSS through jQuery.

  • Object Literal: In this way we can pass multiple CSS properties ad values as an object literal.
$('#tutorialsPoint').css({ 
            'color' : 'green', 
            'background-color' : 'gray', 
            'font-size' : '16px' 
}); 
  • Individual Arguments: Here we can keep the property and value pair as a separate argument.
  • $('#tutorialsPoint')
      .css('color', 'green')
      .css('background-color', 'gray')
      .css('font-size', '16px');
    

    Both of the ways are useful, personally we recommend you to use the Object Literal way.

    Example

    In this following example we have applied multiple CSS on two elements in different ways as we described above.

    
    
    
        Define Multiple CSS Attributes in jQuery
        
        
    
    
    
        
    Define Multiple CSS Attributes in jQuery

    As we have used both the ways to apply CSS through jQuery. Multiple CSS are define in a single call.

    Updated on: 2024-07-01T15:58:25+05:30

    17K+ Views

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements