Two ways to add: 1. Use addClass() to add one or more class names to the selected element, the syntax is "$(selector).addClass("Class Name List")", if you need to add multiple Class names need to be separated by spaces. 2. Use toggleClass() to add a class name to the selected element, the syntax is "$(selector).toggleClass("class name",true);".
The operating environment of this tutorial: windows7 system, jquery3.6.1 version, Dell G3 computer.
Two ways to add a class name to an element using jquery
Use addClass() to add a class name
Use toggleClass() to add a class name
1. Use addClass() to add a class name
addClass () method adds 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.
$(selector).addClass(class)
Parameters | Description |
---|---|
class | Required. Specifies one or more class names. |
Example: Add the class name "p2" to the p element
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-3.6.1.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("button").click(function() { $("p").addClass("p2"); }); }); </script> <style> h1{ color: coral; } .p1{ background-color: yellow; } .p2{ font-size: 120%; color: red; } </head> <body> </style> <h1>这是一个大标题</h1> <p class="p1">这是一个段落。</p> <p class="p1">这是另一个段落。</p> <button>给p元素增加类名p2</button> </body> </html>
2. Use toggleClass( )Add class name
toggleClass() method to switch between adding and removing one or more classes of the selected element.
This method checks the specified class in each element. Adds the class if it does not exist, or removes it if it is set. This is called a toggle effect.
$(selector).toggleClass(class,switch)
However, by using the "switch" parameter, you can specify that only classes be removed or only added.
switch: Optional parameter, Boolean value, specifies whether to only add (true) or remove (false) classes.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-3.6.1.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("button").click(function() { $("p").toggleClass("p2",true); }); }); </script> <style> h1{ color: coral; } .p1{ font-size: 120%; color: red; } .p2{ background-color: yellow; } </head> <body> </style> <h1>这是一个大标题</h1> <p class="p1">这是一个段落。</p> <p class="p1">这是另一个段落。</p> <button>给p元素增加类名p2</button> </body> </html>
[Recommended learning: jQuery video tutorial, web front-end video】
The above is the detailed content of How to add a class name to an element in jquery. For more information, please follow other related articles on the PHP Chinese website!