Home >Web Front-end >JS Tutorial >How to determine whether a specified class exists in jquery
Method: 1. Use the "$(element).hasClass("class name")" statement to check whether the specified class exists. If it exists, return "true"; 2. Use "$(element).attr" ("class")" statement obtains the value of the class attribute. If the value is equal to the class name to be checked, the specified class exists.
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
jquery determines whether the specified class exists
Method 1: Use the hasClass() method
The hasClass() method checks whether the selected element contains the specified class name. This method returns "true" if the selected element contains the specified 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(){ var a=$("p").hasClass("intro"); if(a){ alert("指定类存在"); }else{ alert("指定类不存在"); } }); }); </script> <style type="text/css"> .intro { font-size: 120%; color: red; } </style> </head> <body> <h1>这是一个段落标题</h1> <p class="intro">这是一个段落</p> <p> 这是另外一个段落</p> <button>是否有 p 元素使用了 "intro" 类?</button> </body> </html>
Method 2: Use the attr() method
attr() method can return the attribute value of the selected element.
You can use the attr() method to get the value of the class attribute. If the attribute value is equal to the class name that needs to be checked, the specified class exists.
<!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(){ var a=$("p").attr("class"); if(a=="intro1"){ alert("指定类存在"); }else{ alert("指定类不存在"); } }); }); </script> <style type="text/css"> .intro { font-size: 120%; color: red; } </style> </head> <body> <h1>这是一个段落标题</h1> <p class="intro">这是一个段落</p> <p> 这是另外一个段落</p> <button>是否有 p 元素使用了 "intro1" 类?</button> </body> </html>
Recommended related video tutorials: jQuery Tutorial (Video)
The above is the detailed content of How to determine whether a specified class exists in jquery. For more information, please follow other related articles on the PHP Chinese website!