Home > Web Front-end > JS Tutorial > body text

How to add or remove CSS styles in jQuery

yulia
Release: 2018-09-17 15:04:06
Original
2752 people have browsed it

At work, it is often necessary to use Javascript to change the style of page elements. 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

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

2. removeClass( ) - Remove CSS class

$("#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 the CSS class

If the CSS class already exists, it will is removed; instead, if the CSS class does not exist, it will be added.

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

In actual application, 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.

FAQ:

<label for="TrueName" generated="true" class="msg-error" style="">正确</label>
Copy after login

By addClass("msg-success");

<label for="TrueName" generated="true" class="msg-error msg-success" style="">正确</label>
Copy after login
CSS文件
误:(msg-success将被msg-error覆盖,样式不变)
span.msg-error, label.msg-error{color: #f00;}
span.msg-success, label.msg-success{color: #000;}
正:
span.msg-error, label.msg-error{color: #f00;}
span.msg-success, label.msg-success{color: #000;}
Copy after login

The above is the detailed content of How to add or remove CSS styles in jQuery. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template