Home > Article > Web Front-end > How to change classname in jquery
3 modification methods: 1. Use attr() to modify the value of the class attribute, the syntax is "element object.attr("class","new class name");". 2. Use prop() to modify the value of the class attribute, the syntax is "element object.prop("class","new class name");". 3. Use removeClass() and addClass(), the syntax is "element object.removeClass("old class name").addClass("new class name");".
The operating environment of this tutorial: windows7 system, jquery3.6.1 version, Dell G3 computer.
jquery method to change classname (class name)
Method 1: Use attr() to modify
attr() can set the attributes and values of elements
You only need to modify the value of the class attribute, syntax:
$(selector).attr("class","新类名");
Example
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <script src="js/jquery-3.6.1.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { $("div").attr("class", "box2"); }); }); </script> <style> .box1 { height: 150px; background-color: #AFEEEE; } .box2 { height: 100px; background-color: red; } </style> </head> <body> <div class="box1"></div> <br> <button>改变classname(类名)</button> </body> </html>
Method 2: Use prop() to modify
attr() can set the attributes and values of the element
You only need to modify the class attribute Just change the value and modify the syntax:
$(selector).prop("属性名","新类名");
Example
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <script src="js/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { $("div").prop("class","box1"); }); }); </script> <style> .box1 { height: 150px; background-color: #AFEEEE; } .box2 { height: 100px; background-color: red; } </style> </head> <body> <div class="box2"></div> <br> <button>改变classname(类名)</button> </body> </html>
##Method 3: Modify using removeClass() and addClass()
<!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").removeClass("intro1").addClass("intro2"); }); }); </script> <style> .intro1 { font-size: 120%; color: red; } .intro2 { color: peru; background-color: aquamarine; } </style> </head> <body> <p class="intro1">测试段落</p> <button>改变classname(类名)</button> </body> </html>[Recommended learning:
jQuery tutorial, web front-end video】
The above is the detailed content of How to change classname in jquery. For more information, please follow other related articles on the PHP Chinese website!