How to Apply CSS Styles Using jQuery

How to Apply CSS Styles Using jQuery

We can use jQuery’s .css() method to apply CSS styles on a given web page. 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 CSS styles of DOM elements.

Grammar

$(selector).css(property, value) 

or

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

Let’s see how to use jQuery’s css() method to add styles to HTML elements with some suitable examples.

Example 1

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

<!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 use the css() method provided by jQuery to change the font color and background color of the “p” tag after clicking the button.

<!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> 

Summary

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

Leave a Reply

Your email address will not be published. Required fields are marked *