How to apply CSS style using jQuery?


We can use jquery’s .css() method to apply CSS style on the given webpage. jQuery is a javascript library that helps us manipulate the DOM easily and efficiently using its various helper methods and properties. It allows us to add interactivity to the DOM as well as add and change the CSS styles of the DOM elements.

Syntax

$(selector).css(property, value)

OR

$(selector).css({ property: value, property: value, … })

JQuery css() method accepts either an argument of type object, with key as the CSS property name and value as the desired property value to be set to, or just a pair of comma-separated CSS property name and value.

Let’s understand how to use the css() method, by jQuery, to apply styles to the HTML elements with the help of some suitable examples.

Example 1

In this example, we will change the text color of the “p” tag after clicking the button using css() jQuery method.

<!DOCTYPE html>
<html lang="en">
<head>
   <script src="https://code.jquery.com/jquery-3.6.3.slim.min.js" integrity="sha256-ZwqZIVdD3iXNyGHbSYdsmWP//UBokj2FHAxKuSBKDSo=" crossorigin="anonymous"></script>
   <title>How to apply CSS style using jQuery?</title>
</head>
<body>
   <p class="sample">This is p tag content!</p>
   <button>Click here!</button>  
   <script>
      const button = document.getElementsByTagName('button')[0]
      button.addEventListener('click', function(){
         $('p').css('color', 'red')
      })
   </script>
</body>
</html>

Example 2

In this example, we will change the font color and background color of the “p” tag after clicking the button using css() method provided by jQuery.

<!DOCTYPE html>
<html lang="en">
<head>
   <script src="https://code.jquery.com/jquery-3.6.3.slim.min.js" integrity="sha256-ZwqZIVdD3iXNyGHbSYdsmWP//UBokj2FHAxKuSBKDSo=" crossorigin="anonymous"></script>
   <title>How to apply CSS style using jQuery?</title>
</head>
<body>
   <p class="sample">This is p tag content!</p>
   <button>Click here!</button>  
   <script>
      const button = document.getElementsByTagName('button')[0]
      button.addEventListener('click', function() {
         $('p').css({ 'color': 'white', 'background-color': 'black' })
      })
   </script>
</body>
</html>

Conclusion

In this article, we learned about the css() method provided by jQuery, and we used it to apply the CSS style properties to the DOM elements, with the help of 2 examples, In the first example, we changed the “text-color” of the content on a button click, and in the second example, we changed the “text-color” and “background-color” of the content on the click of a button.

Updated on: 22-Feb-2023

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements