Skip to main content

CSS Classes and CSS Manipulation


Introduction to CSS Classes and CSS Manipulation in jQuery

CSS (Cascading Style Sheets) is a style sheet language used for describing the look and formatting of a document written in HTML or XML. CSS classes offer a way to select elements that have a specific attribute. This attribute is often used to apply styles, manipulate the DOM, or create complex animations.

jQuery is a powerful JavaScript library that makes HTML document traversal and manipulation, event handling, and animation much simpler with an easy-to-use API that works across a multitude of browsers. jQuery provides a variety of methods for manipulating CSS and classes in an HTML document.

In this tutorial, we will cover how to use jQuery to manipulate CSS classes and styles in an HTML document.

Adding CSS Classes in jQuery

To add a CSS class to an HTML element with jQuery, you use the addClass() method. Here's an example:

$('p').addClass('highlight');

In this example, the addClass() method adds the 'highlight' class to all paragraph elements in the HTML document.

Removing CSS Classes in jQuery

To remove a CSS class from an HTML element with jQuery, you use the removeClass() method. Here's an example:

$('p').removeClass('highlight');

In this example, the removeClass() method removes the 'highlight' class from all paragraph elements in the HTML document.

Toggling CSS Classes in jQuery

To toggle a CSS class on an HTML element with jQuery, you use the toggleClass() method. This method adds the specified class if it is not present and removes it if it is present. Here’s an example:

$('p').toggleClass('highlight');

In this example, the toggleClass() method toggles the 'highlight' class on all paragraph elements in the HTML document.

Manipulating CSS with jQuery

jQuery also allows you to directly manipulate the CSS of an HTML element. You can set the CSS properties of an element using the css() method. Here's an example:

$('p').css('color', 'blue');

In this example, the css() method changes the text color of all paragraph elements to blue.

You can also retrieve the value of a CSS property using the css() method. Here's an example:

var color = $('p').css('color');

In this example, the css() method retrieves the text color of the first paragraph element in the HTML document.

Conclusion

This tutorial covered how to manipulate CSS classes and styles in an HTML document using jQuery. We learned how to add, remove, and toggle CSS classes, as well as how to set and retrieve CSS properties. With these methods, you can control the appearance and layout of your HTML elements dynamically.