Home > Article > Web Front-end > How to replace class style in jquery
Replacement method: 1. Use the removeClass() method to remove the old class style, and the addClass() method to add a new class style; 2. Use the attr() method to modify the class attribute and directly replace it with the new one. The class class is enough, the syntax is "$(element).attr("class","new class name")".
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
jquery replacement class style
Method 1: Use removeClass() and addClass() methods
Use the removeClass() method to remove the old class style, and use the addClass() method to add a new class style
<!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").removeClass("old-class").addClass("new-class") ; }); }); </script> <style type="text/css"> .old-class{ border: 1px solid red; background-color: #FFC0CB; } .new-class{ border: 2px solid green; background-color: #55aa7f; color: white; } </style> </head> <body> <p class="old-class">hello,测试文字</p> <button>替换类样式</button> </body> </html>
Method 2: Use attr()
Use the attr() method to modify the class attribute and replace it directly with the new class class
<!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").attr("class","new-class"); }); }); </script> <style type="text/css"> .old-class{ border: 1px solid red; background-color: #FFC0CB; } .new-class{ border: 2px solid green; background-color: #55aa7f; color: white; } </style> </head> <body> <p class="old-class">hello,测试文字</p> <button>替换类样式</button> </body> </html>
Recommended related video tutorials: jQuery Tutorial(Video)
The above is the detailed content of How to replace class style in jquery. For more information, please follow other related articles on the PHP Chinese website!