HTML - DOMTokenList add() 方法



HTML DOMTokenList 的 **add()** 方法用于将参数中指定的一个或多个标记添加到 DOMTokenList。

语法

domtokenlist.add(token);

参数

此方法接受单个参数,如下所示。

参数 描述
token 它表示要添加到 DOMTokenList 的标记名称。

返回值

它不返回任何值。

HTML DOMTokenList 'add()' 方法示例

以下示例说明了 DOMTokenList add() 方法的实现。

向元素添加类

以下示例说明了如何使用 **add()** 方法向任何元素添加类。添加的类会更改元素的背景色和文本颜色。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOMTokenList add() Method
    </title>
    <style>
        .color {
            background-color: #04af2f;
            color: white;
        }
    </style>
</head>
<body>
    <button onclick="fun()">Click me</button>
    <p>Hii..</p>
    <p id="add">Welcome to Tutorials Point...</p>
    <script>
        function fun() {
            let x = document.getElementById("add").classList;
            x.add("color");
        }
    </script>
</body>
</html>

向元素添加多个类

在以下示例中,我们向一个段落元素添加了多个类。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOMTokenList add() Method
    </title>
    <style>
        .color {
            background-color: #04af2f;
            color: white;
        }
        .font {
            font-size: 40px;
        }
        .align {
            text-align: center;
        }
    </style>
</head>
<body>
    <button onclick="fun()">Click me</button>
    <p>Hii..</p>
    <p id="add">Welcome to Tutorials Point...</p>
    <script>
        function fun() {
            let x = document.getElementById("add").classList;
            x.add("color", "font", "align");
        }
    </script>
</body>
</html>

获取元素的类标记

在以下示例中,我们获取添加到 HTML 文档中的类的名称。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>HTML DOMTokenList add() Method</title>
    <style>
        .color {
            background-color: #04af2f;
            color: white;
        }
        .font {
            font-size: 40px;
        }
        .align {
            text-align: center;
        }
    </style>
</head>
<body>
    <button onclick="fun()">Click me</button>
    <p>Hii..</p>
    <p id="add">Welcome to Tutorials Point...</p>
    <p>Added class tokens are :</p>
    <p id="token"></p>
    <script>
        function fun() {
            let x = document.getElementById("add").classList;
            x.add("color", "font", "align");
            document.getElementById("token").innerHTML = x;
        }
    </script>
</body>
</html>

支持的浏览器

方法 Chrome Edge Firefox Safari Opera
add() 是 8 是 12 是 3.6 是 5.1 是 12.1
html_domtokenlist_reference.htm
广告
© . All rights reserved.