如何用jQuery检查一个元素是否包含一个类

如何用jQuery检查一个元素是否包含一个类

方法1:使用hasClass()方法: hasClass()是jQuery内置的一个方法,用于检查指定的类名的元素是否存在。它返回一个布尔值,指定该元素中是否存在该类。这可以被用来检查多个类。

语法:

$('element').hasClass('className')

示例:

<!DOCTYPE html>
<html>
      
<head>
    <title>
        How to check an element contains
        a class using jQuery?
    </title>
      
    <script src=
        "https://code.jquery.com/jquery-3.3.1.min.js">
    </script>
</head>
  
<body>
    <h1 style="color: green">
        GeeksforGeeks
    </h1>
      
    <b>
        How to check an element contains
        a class using jQuery?
    </b>
  
    <p class="example-class">
        This element has "example-class".
    </p>
  
    <p>Does the element have class?
        <span class="output"></span>
    </p>
  
    <button onclick="checkForClass()">
        Click to check
    </button>
      
    <!-- Script to use hasClass() method to
        check the existence of class name -->
    <script type="text/javascript">
        function checkForClass() {
            classCheck = $('p').is('.example-class');
            document.querySelector('.output').textContent
                    = classCheck;
        }
    </script>
</body>
  
</html>                    

输出:
如何用jQuery检查一个元素是否包含一个类?

方法2:使用is()方法 :这与上述方法类似,如果需要,可以用来检查更多的属性。所需的元素被选中,类的名称像CSS类选择器一样被传递。它返回一个布尔值,指定该类是否存在于该元素中。这可以用来检查多个类。

语法:

$('element').is('.className')

示例:

<!DOCTYPE html>
<html>
      
<head>
    <title>
        How to check an element contains
        a class using jQuery?
    </title>
      
    <script src=
        "https://code.jquery.com/jquery-3.3.1.min.js">
    </script>
</head>
  
<body>
    <h1 style="color: green">
        GeeksforGeeks
    </h1>
      
    <b>
        How to check an element contains
        a class using jQuery?
    </b>
  
    <p class="example-class">
        This element has "example-class".
    </p>
  
    <p>Does the element have class? 
        <span class="output"></span>
    </p>
  
    <button onclick="checkForClass()">
        Click to check
    </button>
      
    <!-- Script to use is() method to
        check the existence of class name -->
    <script type="text/javascript">
        function checkForClass() {
            classCheck = $('p').is('.example-class');
            document.querySelector('.output').textContent
                    = classCheck;
        }
    </script>
</body>
  
</html>                    

输出:
如何用jQuery检查一个元素是否包含一个类?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程