Judgment method: 1. Use hasClass() to check whether the element contains the specified class name, the syntax is "element object.hasClass("class name")"; 2. Use attr() to get the value of the class attribute, and judge Whether the attribute value is equal to the specified class name, the syntax is "element object.attr("class")=="class name"".
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
There are two ways for jquery to determine whether an element contains the specified class name:
Use hasClass()
Use attr( )
Method 1: Use the hasClass()
hasClass() method to check 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(){ if($("p").hasClass("intro")){ console.log("有指定类名"); }else{ console.log("没有指定类名"); } }); }); </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 attr()
attr() to get the value of the class attribute, which is the class Name
only needs to determine whether the attribute value is equal to the specified class name.
<!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(){ if($("p").attr("class")=="intro"){ console.log("有指定类名"); }else{ console.log("没有指定类名"); } }); }); </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>
[Recommended learning: jQuery video tutorial, web front-end video】
The above is the detailed content of How does jquery determine whether an element has a specified class name?. For more information, please follow other related articles on the PHP Chinese website!