HTML - DOMTokenList replace() 方法



HTML DOMTokenList **replace()** 方法用於將 DomTokenList 中已存在的令牌替換為引數中指定的新的令牌。如果引數中指定的舊令牌不存在,則返回 **false**,並且不會將新令牌新增到列表中。

語法

domtokenlist.replace(old, new);

引數

此方法接受如下所示的兩個引數。

引數 描述
舊的 它表示列表中現有的令牌。
新的 它表示將替換舊令牌的新令牌。

返回值

它返回一個布林值,其中 true 表示令牌已成功替換,如果未替換則返回 false。

HTML DOMTokenList 'replace()' 方法示例

以下示例將 class='align' 替換為新的 class='right'。

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

支援的瀏覽器

方法 Chrome Edge Firefox Safari Opera
replace() 是 61 是 17 是 49 是 10.1 是 48
html_domtokenlist_reference.htm
廣告