Home > Article > Web Front-end > How to use jquery addclass()
In jquery, the addclass() method is used to add one or more classes to the selected element. The syntax is "$(selector).addClass("class name")"; if you need to add multiple classes , you need to use spaces to separate class names.
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
In jquery, the addclass() method is used to add one or more classes to the selected element.
This method does not remove the existing class attribute, but only adds one or more class attributes.
Tip: If you need to add multiple classes, please use spaces to separate class names.
Syntax
$(selector).addClass(class)
Also use functions to add classes to selected elements
$(selector).addClass(function(index,oldclass))
Example:
Add a class to the first p element
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-1.10.2.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("button").click(function() { $("p:first").addClass("intro"); }); }); </script> <style type="text/css"> .intro { font-size: 120%; color: red; } </style> </head> <body> <h1>这是一个大标题</h1> <p>这是一个段落。</p> <p>这是另一个段落。</p> <button>向第一个 p 元素添加一个类</button> </body> </html>
Add two classes to the element
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-1.10.2.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("button").click(function() { $("p:first").addClass("intro note"); }); }); </script> <style type="text/css"> .intro { font-size: 120%; color: blue; } .note { background-color: yellow; } </style> </head> <body> <h1>这是一个大标题</h1> <p>这是一个段落。</p> <p>这是另一个段落。</p> <button>向第一个 p 元素添加一个类</button> </body> </html>
[Recommended learning: jQuery video tutorial, web front-end】
The above is the detailed content of How to use jquery addclass(). For more information, please follow other related articles on the PHP Chinese website!