Two modification methods: 1. Use attr() to modify the value of the class attribute, the syntax is "dom element object.attr("class","new class name")"; 2. After removing the old class To add a new class, the syntax is "dom element object.removeClass("old class name").addClass("new class name")".
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
jquery method of modifying the class name of a dom element
Method 1: Directly use attr() to modify the value of the class attribute
attr() method can set the attribute value of the selected element.
<!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","intro2"); }); }); </script> <style type="text/css"> .intro1 { font-size: 120%; color: red; } .intro2 { font-size: 120%; color: green; } </style> </head> <body> <h1>这是一个段落标题</h1> <p class="intro1">这是一个段落</p> <p> 这是另外一个段落</p> <button>修改p元素的 "intro1" 类</button> </body> </html>
Method 2: Use removeClass() and addClass()
Use removeClass() first Remove the specified class
and then use addClass() to add a new 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:first").removeClass("intro1").addClass("intro2"); }); }); </script> <style type="text/css"> .intro1 { font-size: 120%; color: red; } .intro2 { font-size: 120%; color: green; } </style> </head> <body> <h1>这是一个段落标题</h1> <p class="intro1">这是一个段落</p> <p> 这是另外一个段落</p> <button>修改p元素的 "intro1" 类</button> </body> </html>
[Recommended learning: jQuery video tutorial、web front-end video】
The above is the detailed content of How to modify the class name of dom element in jquery. For more information, please follow other related articles on the PHP Chinese website!