How to use jQuery to manipulate CSS styles of elements dynamically



Image not found!!

To manipulate CSS styles of elements dynamically using jQuery, you can use the css() method provided by jQuery. This method allows you to get or set CSS properties for the selected elements. Here's a basic example:

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 Manipulation</title> <!-- Include jQuery library --> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <style> /* Some initial styles for demonstration */ .changeable { width: 200px; height: 100px; background-color: lightblue; } </style> </head> <body> <div class="changeable">This is a changeable element</div> <script> // Wait for the document to be ready $(document).ready(function() { // Change background color to red $('.changeable').css('background-color', 'red'); // Add a new CSS property dynamically $('.changeable').css('border', '2px solid black'); // You can also manipulate multiple properties at once using an object $('.changeable').css({ 'font-size': '20px', 'color': 'white' }); }); </script> </body> </html>

In this example:

  1. Include the jQuery library in your HTML document. You can download it and host it locally or use a CDN, as shown in the example.

  2. Define some initial styles using CSS, and create an element with a class name changeable.

  3. In the <script> section, use the $(document).ready() function to ensure that your jQuery code executes after the document has finished loading.

  4. Use the css() method to manipulate the CSS styles of the selected element with the class name changeable. You can specify individual properties and values or provide an object with multiple properties.

This is just a basic example, and you can customize it further based on your specific requirements. Keep in mind that using jQuery for basic CSS manipulation may not be necessary in modern web development, where CSS and vanilla JavaScript can often achieve the same results.