In front-end development, we often need to operate the class attribute of DOM elements to achieve various interactive effects. In jQuery, we can easily manipulate the class attribute of elements. But sometimes, we need to delete a specific class, what should we do at this time? This article will introduce how to use jQuery to remove a class.
1. Use the removeClass method
jQuery provides a method called removeClass to delete the class of an element. The format is as follows:
$(selector).removeClass(className)
Among them, selector refers to the selector of the element to be operated, and className is the name of the class to be deleted.
For example, if we want to delete the class named "active" of an element with the id "test", we can write like this:
$("#test").removeClass("active");
This method will specify the selected element The class is deleted from the class list.
Note that if you want to delete multiple classes, you need to separate them with spaces, for example:
$("#test").removeClass("active hidden");
2. Use the attr method
In addition to using the removeClass method, We can also use the attr method to delete a class.
$(selector).attr("class", "")
This method will set the value of the class attribute of the selected element to an empty string, which is equivalent to deleting all classes.
$("#test").attr("class", "");
3. Use the toggleClass method
In addition to deleting the class, sometimes we also need to switch the class. Taking the toggleClass method as an example, it can add or delete the specified class. If the element already has the specified class, the class will be deleted; otherwise, the class will be added.
We can pass two parameters to the toggleClass method, one is the class name to be switched, and the other is the optional switch parameter. When the switch parameter is true, the class will be added; when the switch parameter is false, the class will be deleted.
The following is the format of the toggleClss method:
$(selector).toggleClass(className, switch)
For example, we have a button, and its class can be used to switch the button state (such as switching to "active" or "disabled"), you can Write like this:
$("#btn").click(function(){ $(this).toggleClass("active disabled"); });
When we click the button, its class will be added or deleted accordingly.
Summary
In short, it is very simple to remove a class in jQuery, just use the removeClass or attr method. If you need to switch classes, use the toggleClass method. These methods are commonly used in jQuery. Mastering them can make you get twice the result with half the effort in front-end development.
The above is the detailed content of jquery removes a class. For more information, please follow other related articles on the PHP Chinese website!