Home >Web Front-end >JS Tutorial >jQuery Add/Remove CSS Class Implementation Code_jquery

jQuery Add/Remove CSS Class Implementation Code_jquery

WBOY
WBOYOriginal
2016-05-16 18:34:49986browse

One way is to change the CSS class (Class) of the page element. In traditional Javascript, we usually do this by processing the classname attribute of HTML Dom; jQuery provides three methods to achieve this function, although they The idea is similar to the traditional method, but it saves a lot of code. Still the same sentence - "jQuery makes JavaScript code concise!"

1. addClass() - Add CSS class

Copy code The code is as follows:

$("#target").addClass("newClass");
//#target refers to the need The ID of the element to which the style is added
//newClass refers to the name of the CSS class

2. removeClass() - removes the CSS class
Copy code The code is as follows:

$("#target").removeClass("oldClass");
//#target refers to the ID of the element whose CSS class needs to be removed
//oldClass refers to the name of the CSS 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.
Copy code The code is as follows:

$("#target").toggleClass("newClass ")
//If the element with ID "target" has a CSS style defined, it will be removed;
//On the contrary, the CSS class "newClass" will be assigned to the ID.

4.hasClass("className") - Determine whether CSS already exists

In practical applications, we often define these CSS classes first, and then Change the page element style through Javascript event triggering (such as clicking a link). In addition, jQuery also provides a method hasClass("className") to determine whether an element has been assigned a CSS class.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn