jQuery Tutorial: Get/Set CSS Properties 🎯

beginner
13 min

jQuery Tutorial: Get/Set CSS Properties 🎯

Welcome to our comprehensive guide on using jQuery to manipulate CSS properties! By the end of this tutorial, you'll be able to confidently adjust and modify styles in your web projects. 📝 Note: This guide is designed for both beginners and intermediate learners, so let's dive right in!

Understanding the Basics 📝

What is jQuery?

jQuery is a JavaScript library that simplifies HTML document traversing, event handling, and animating. It's particularly useful for manipulating CSS properties with ease.

Getting Started 💡 Pro Tip:

To use jQuery in your projects, you'll first need to include its library in your HTML file:

html
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

Selecting Elements 📝 Note:

Before we dive into setting and getting CSS properties, let's understand how to select HTML elements using jQuery.

javascript
// Selecting an element by its ID $('#myElement') // Selecting elements by their class $('.myClass') // Selecting all elements with a specific tag $('p')

Getting CSS Properties 💡 Pro Tip:

To retrieve the current CSS property value of an element, you can use the css() method with no arguments.

javascript
// Get the current font-size of the #myElement var fontSize = $('#myElement').css('font-size');

Setting CSS Properties 💡 Pro Tip:

To set a new CSS property value, pass the property name and the new value as arguments to the css() method.

javascript
// Change the font-size of #myElement to 20px $('#myElement').css('font-size', '20px');

Advanced Example 💡 Pro Tip:

Let's create a simple real-world example: Changing the background color of a button on click.

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>jQuery CSS Properties</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <button id="changeColor">Change Background</button> <script> $(document).ready(function() { $('#changeColor').click(function() { // Change the background color of the button $(this).css('background-color', 'blue'); }); }); </script> </body> </html>

Quiz 💡 Pro Tip:

What jQuery function do we use to retrieve the current CSS property value of an element?

That's it for this lesson! With these concepts under your belt, you're well on your way to mastering jQuery's CSS manipulation capabilities. Happy coding! 🎯