Home >Web Front-end >Front-end Q&A >How to add a class in jquery
Two methods: 1. Use attr(), just add a value to the class attribute, the syntax is "element object.attr("class","class name");". 2. Use addClass() to add one or more classes. The syntax is "element object.addClass("class name")". If you add multiple classes, separate the class names with spaces.
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
Two ways to add a class in jquery
1. Use attr()
attr () can set the attribute value of the selected element, and add the class when the attribute is "class".
This method is used to add a new class when there is no class before.
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").attr("class","intro"); }); }); </script> <style type="text/css"> .intro { font-size: 120%; color: red; } </style> </head> <body> <h1>This is a heading</h1> <p>This is a paragraph.</p> <p>This is another paragraph.</p> <button>向第一个 p 元素添加一个类</button> </body> </html>
##2. Use addClass()
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. If you need to add multiple classes, separate the class names with spaces. Example: Add a class to the second 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:nth-child(3)").addClass("intro"); }); }); </script> <style type="text/css"> .intro { font-size: 120%; color: red; } </style> </head> <body> <h1>一个大标题</h1> <p>第一个段落</p> <p>第二个段落</p> <p>第三个段落</p> <button>向第二个 p 元素添加一个类</button> </body> </html>[Recommended learning:
jQuery video tutorial, web front-end video】
The above is the detailed content of How to add a class in jquery. For more information, please follow other related articles on the PHP Chinese website!