replace() 方法在 DOMTokenList interface replaces an existing token with a new token. If the first token doesn't exist, replace() 返回 false immediately, without adding the new token to the token list.

句法

tokenList.replace(oldToken, newToken);
					

参数

oldToken
DOMString representing the token you want to replace.
newToken
DOMString representing the token you want to replace oldToken with.

返回值

A boolean value, which is true if oldToken was successfully replaced, or false 若不。

注意 : In older browsers, replace() returns void.

范例

In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList 使用 Element.classList . We then replace a token in the list, and write the list into the <span> 's Node.textContent .

First, the HTML:

<span class="a b c"></span>
					

Now the JavaScript:

let span = document.querySelector("span");
let classes = span.classList;
let result = classes.replace("c", "z");
console.log(result);
if (result) {
  span.textContent = classes;
} else {
  span.textContent = 'token not replaced successfully';
}
					

输出看起来像这样:

Polyfill

The following polyfill will add the replace method to the DOMTokenList class.  The following code will only work with IE10-11 . To use with earlier versions of IE, refer to the polyfill at element.classList#Polyfill

DOMTokenList.prototype.replace = function (a, b) {
    if (this.contains(a)) {
        this.add(b);
        this.remove(a);
        return true;
    }
    return false;
}
					

规范

规范 状态 注释
DOM
The definition of 'replace()' in that specification.
实时标准 初始定义

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
replace Chrome 61 Edge 17 Firefox 49 IE 不支持 No Opera 48 Safari 10.1 WebView Android 61 Chrome Android 61 Firefox Android 49 Opera Android 45 Safari iOS 10.3 Samsung Internet Android 8.0
return() 's value is a boolean, not void as it used to be. Chrome 67 Edge 18 Firefox 61 IE 不支持 No Opera 54 Safari 12 WebView Android 67 Chrome Android 67 Firefox Android 61 Opera Android 48 Safari iOS 12 Samsung Internet Android 9.0

图例

完整支持

完整支持

不支持

不支持

元数据

  • 最后修改: