JQuery adds and changes and removes CSS classes and determines if CSS already exists

  • 2020-03-30 03:44:40
  • OfStack

Changing the style of page elements using Javascript is also possible, but there is no more concise way, the answer is yes, now with jQuery, it seems to make Js code a lot of weight, true to the saying: "jQuery makes Javascript code concise!" , let's take a look at how jquery adds and removes CSS classes:

1. RemoveClass () - removes CSS classes


$("#target").removeClass("oldClass"); 
//#target refers to the ID of the element that needs to be removed from the CSS class
//oldClass  Refers to the CSS The name of the class 

2. AddClass () - add a CSS class


$("#target").addClass("newClass"); 
//#target refers to the ID of the element that needs to be styled
//newClass  Refers to the CSS The name of the class 

3. ToggleClass () - add or remove a CSS class: if the CSS class already exists, it will be removed; Conversely, if the CSS class does not exist, it will be added.


$("#target").toggleClass("newClass") 
//If the element with the ID "target" already has a CSS style defined, it is removed.
// On the other hand, CSS Class" newClass "Will be assigned to the ID

HasClass ("className") - determines if CSS already exists

In practice, it is common to define these CSS classes and then to change the style of a page element via Javascript events, such as the click of a button. In addition, jQuery provides a method called hasClass (" className ") to determine whether an element has been assigned to a CSS class. By the way, tell the novice front-end development, jquery is worth having, have time to study it.


Related articles: