Jquery method to add a class to an element: 1. Use the attr() method, syntax "$(selector).attr("class","class name")"; 2. Use the addClass() method, Syntax "$(selector).addClass("class name")".
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
Add a class to the element in jquery
1. Use the attr() method
The attr() method sets or returns the attribute value of the selected element.
According to the different parameters of this method, its working method is also different.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-1.10.2.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { $("p:first").attr("class","intro"); }); }); </script> <style> .intro { font-size: 150%; color: red; } </style> </head> <body> <h1>这是一个标题</h1> <p>这是一个段落。</p> <p>这是另一个段落。</p> <button>给第一个P元素添加一个类名</button> </body> </html>
2. Use the addClass() method
addClass() method to add one or more class names to the selected element .
This method does not remove the existing class attribute, but only adds one or more class names to the class attribute.
Tip: If you need to add multiple classes, please use spaces to separate class names.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-1.10.2.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { $("p:first").addClass("intro"); }); }); </script> <style> .intro { font-size: 150%; color: pink; } </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 add a class to an element in jquery. For more information, please follow other related articles on the PHP Chinese website!