如何用jQuery为一个已经有类的元素添加新的类

如何用jQuery为一个已经有类的元素添加新的类

在这篇文章中,我们将学习如何使用jQuery为一个已经有类的元素添加一个新的类。为了添加一个新的类,我们使用jQuery addClass()方法。addClass()方法是用来添加更多的类和它们的属性到每个选定的元素。它也可以用来改变所选元素的属性。

语法:

$(selector).addClass(className);

参数:它接受一个参数 “className”,即要添加的新类的名称。

示例:

<!DOCTYPE html>
<html lang="en">
  
<head>
    <style>
        .GFG1 {
            color: green;
            font-weight: bold;
        }
  
        .GFG2 {
            font-size: 24px;
        }
    </style>
  
    <!-- Import jQuery cdn library -->
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
  
    <script>
        (document).ready(function () {
            ("button").click(function () {
                $("p").addClass("GFG2");
            });
        });
    </script>
</head>
  
<body style="text-align: center;">
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
  
    <h3>
        How to add a new class to an element that
        <br>already has a class using jQuery?
    </h3>
  
    <p class="GFG1">
        GeeksforGeeks computer science portal
    </p>
  
    <button>Click Here!</button>
</body>
  
</html>

输出:

在点击按钮之前:

如何用jQuery为一个已经有类的元素添加新的类?

点击按钮后:

如何用jQuery为一个已经有类的元素添加新的类?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程