如何在jQuery中不使用addClass()方法为一个元素添加类

如何在jQuery中不使用addClass()方法为一个元素添加类

任务是在jQuery的帮助下,不使用addClass()方法为元素添加一个新的类。有两种方法在下面讨论。

方法1:为了执行操作,我们可以使用toggleClass()方法来切换我们想要添加到元素的类。

  • 示例:
<!DOCTYPE HTML>
<html>
  
<head>
    <title>
        How to add class to an element without
        addClass() method in jQuery ?
    </title>
  
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
    </script>
  
    <style>
        #el {
            background: green;
        }
  
        .newClass {
            color: white;
        }
    </style>
</head>
  
<body style="text-align:center;">
  
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
  
    <p id="GFG_UP"></p>
  
    <p id="el">This is the element</p>
  
    <button onclick="GFG_Fun()">
        Click Here
    </button>
  
    <p id="GFG_DOWN"></p>
  
    <script>
        var el_up = document.getElementById('GFG_UP');
        var el_down = document.getElementById('GFG_DOWN');
  
        el_up.innerHTML = "Click on the button to "
                    + "perform the operation.";
                      
        function GFG_Fun() {
            $('#el').toggleClass('newClass');
            el_down.innerHTML = "Class has been added";
        }
    </script>
</body>
  
</html>
  • 输出:
    如何在jQuery中不使用addClass()方法为一个元素添加类?

方法2:我们也可以使用attr()方法prop()方法为元素添加一个新的属性’class’。

  • 示例:
<!DOCTYPE HTML>
<html>
  
<head>
    <title>
        How to add class to an element without
        addClass() method in jQuery ?
    </title>
  
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
    </script>
  
    <style>
        #el {
            background: green;
        }
  
        .newClass {
            color: white;
        }
    </style>
</head>
  
<body style="text-align:center;">
  
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
      
    <p id="GFG_UP"></p>
  
    <p id="el">This is the element</p>
      
    <button onclick="GFG_Fun()">
        Click Here
    </button>
      
    <p id="GFG_DOWN"></p>
  
    <script>
        var el_up = document.getElementById('GFG_UP');
        var el_down = document.getElementById('GFG_DOWN');
  
        el_up.innerHTML = "Click on the button to "
                        + "perform the operation.";
                          
        function GFG_Fun() {
            $('#el').attr('class', 'newClass');
            el_down.innerHTML = "Class has been added";
        }
    </script>
</body>
</html>
  • 输出:
    如何在jQuery中不使用addClass()方法为一个元素添加类?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程