Class operations operate on element styles by manipulating the element’s class name. When element styles are complex, using CSS () methods requires long code in CSS, which is neither beautiful nor convenient. By writing a class name, it is convenient to add or remove the class name. The following code demonstrates adding, removing, and switching classes.

1. Preparation

Prepare an HTML page, and then use jQuery code to manipulate the page. The HTML code is as follows.

< / span > < / p > < p style = “background-color: red; } > >

> Line 2 defines a style for the Current class with a red background color, and lines 5 and 6 define two DIV elements with class name Current.

2. AddClass (

The addClass() method adds one or more class names to the selected element, with the basic syntax shown below.

$(selector).addClass(className)

In the above code, ClassName represents the className to be added, as shown in the sample code below

< script > $(” div “). Click (function () {$(this). The addClass (” current “); }); < / script > after the above code execution, click the “add the name of the class” button in a web page, will be on the div elements added to the current name of the class, the background color change to red.

If you add multiple classes and separate the class names with Spaces, the sample game code is as follows.

$(this). The addClass (” current current1…” );

  1. RemoveClass () to remove the class

The removeClass() method removes one or more classes from the selected element, with the basic syntax shown below.

In the above code, the className parameter can be passed in one or more class names, separated by Spaces. If the parameter is omitted, all class names are removed. Here’s a code demonstration.

  1. ToggleClass () to switch classes

The toggleClass() method is used to add or remove a class from an element, if it doesn’t exist, or remove it if it does. The basic syntax is shown below.

$(selector).toggleclass (className, switch); $(selector).toggleclass (className, switch); The switch parameter specifies that only classes are to be removed or only classes are to be added. Set to true for added and false for removed.

The following code demonstrates the use of toggleClass().

< script > $(” div “). Click (function () {$(this). ToggleClass (” current “); }); < / script > after the above code execution, click on the page of “class name” switch button, when the presence of the current class names on div elements, has been removed, or add. Can realize the font background color switch effect.