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
廣告