Adding and Removing CSS Classes with jQuery
Apart from the methods to delete elements and attributes, jQuery also includes methods to add and remove CSS classes. Refer to the following jQuery lesson by Mytour to learn how to add and remove CSS classes with jQuery.
1. Adding and Removing CSS Classes with jQuery
2. The addClass() Method in jQuery
3. The removeClass() Method in jQuery
4. The toggleClass() Method in jQuery
1. Adding and Removing CSS Classes with jQuery
jQuery encompasses several methods such as addClass(), removeClass(), toggleClass(), ... to manipulate CSS classes assigned to HTML elements.
2. The addClass() Method in jQuery
The addClass() method in jQuery is used to add one or more classes to the selected elements.
Example: The example below illustrates how to add the .page-header class to the h1 element and the .highlight class to the p element containing the .hint class when clicking the button.
The output result looks like this:
Additionally, we can also add multiple classes to multiple elements at once. Simply specify a list of classes separated by spaces in the addClass() method, as shown in the example below:
The output result looks like this:
3. The removeClass() Method in jQuery
Similarly, we can use the removeClass() method in jQuery to remove classes from elements. The removeClass() method can remove one class, multiple classes, or all classes at once from the selected elements.
Example: In the example below, remove the .page-header class from the h1 element, the .hint class, and the .highlight class from the p element when clicking the button:
The output result looks like this:
If the removeClass() method is called without arguments, it will remove all classes from the selected elements, as shown in the example below:
The output result looks like this:
4. The toggleClass() Method in jQuery
The toggleClass() method in jQuery is used to add or remove one or more classes from selected elements. If the selected element already has a class, the method will remove that class. Conversely, if the element does not have a class, the method will add one.
Example: The following example illustrates how to use the toggleClass() method in jQuery to add or remove classes in the selected element:
The output result looks like this:
In this tutorial, Mytour has just guided you on how to add and remove CSS classes using jQuery. In the next tutorial, Mytour will continue to guide you on how to retrieve and set CSS properties using jQuery. Additionally, if you have any questions or need further clarification, feel free to leave your comments below the article.