Add/Remove CSS class implementation code using jquery

Source: Internet
Author: User

One of the methods is to change the CSS class of page elements. In traditional JavaScript, we usually implement it by processing the classname feature of HTML Dom; jquery provides three methods to implement this function. Although they share the same idea with traditional methods, they save a lot of effort. Code . -"Jquery makes JavaScript code concise !"

1. addclass ()-add CSS class Copy codeThe Code is as follows: $ ("# target"). addclass ("newclass ");
// # Target indicates the ID of the element to add a style.
// Newclass refers to the CSS Class Name

2. removeclass ()-remove the CSS class Copy codeThe Code is as follows: $ ("# target"). removeclass ("oldclass ");
// # Target indicates the ID of the element to be removed from the CSS class.
// Oldclass 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.Copy codeThe Code is as follows: $ ("# 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 CSS exists

In practical use, we often define these CSS classes first, and then use JavaScript event triggers (such as clicking a link) 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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.