Add/change/remove CSS classes in jQuery
You can also use Javascript to change the page element style. But is there any more concise method? The answer is yes. Now with jQuery, it seems that Javascript code has been reduced a lot, the following sentence was fulfilled: "jQuery makes JavaScript code concise! ", Let's get down to the truth and see how jquery adds and removes CSS classes:
1. removeClass ()-remove the CSS class
. Code
- $ ("# Target"). removeClass ("oldClass ");
- // # Target indicates the ID of the element to be removed from the CSS class.
- // OldClass refers to the CSS Class Name
2. addClass ()-add CSS class. Front-end UI framework sharing
. Code
- $ ("# Target"). addClass ("newClass ");
- // # Target indicates the ID of the element to add a style.
- // NewClass refers to the CSS Class Name
3. toggleClass ()-add or remove a CSS class: If the CSS class already exists, it will be removed. On the contrary, if the CSS class does not exist, it will be added.
. Code
- $ ("# Target"). toggleClass ("newClass ")
- // If the element whose ID is "target" has defined the CSS style, it will be removed;
- // Conversely, the CSS class "newClass" will be assigned to this ID.
4. hasClass ("className")-determine whether the CSS front-end UI framework already exists
In practice, we usually define these CSS classes first, and then use Javascript events to trigger (such as clicking a button) to change the page element style. In addition, jQuery provides a hasClass ("className") method to determine whether an element has been assigned to a CSS class. By the way, I would like to tell the beginner in front-end development that jquery is worth it. If you have time, study it.