Two judgment methods: 1. Using hasClass(), you can check whether the selected element contains the specified class (class name), the syntax is "specified element object.hasClass("class name")", if it contains Returns true if the specified class is not included, or false if it is not included. 2. Use attr() and the "==" operator, with the syntax "specified element object.attr("class")=="class name"", to check whether the element's class attribute value is equal to the specified class name, and if true is returned Indicates inclusion.
The operating environment of this tutorial: windows7 system, jquery3.6.0 version, Dell G3 computer.
Two methods for jquery to determine whether an element contains a specified class:
Method 1: Use hasClass() to determine
hasClass() method can check whether the selected element contains the specified class (class name).
If the selected element contains the specified class, this method returns true, if it does not, it returns false.
Example: Check whether the
element contains "intro" Class
<!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(){ console.log($("p").hasClass("intro")); }); }); </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>
The return value is true, so the specified p element contains "intro" kind.
Method 2: Use attr() and "==" to determine
element contains the "intro" class
$(document).ready(function(){ $("button").click(function(){ console.log($("p").attr("class")=="intro"); }); });
jQuery video tutorial, web front-end video】
The above is the detailed content of How to determine whether an element contains a specified class in jquery. For more information, please follow other related articles on the PHP Chinese website!