DOMTokenList.replace()

翻译不完整。 请帮助我们翻译这篇文章!

DOMTokenList接口的 replace() 方法可以将列表中一个已存在的token替换为一个新token。如果第一个参数token在列表中不存在, replace() 立刻返回false ,而不会将新token字符串添加到列表中。

语法

tokenList.replace(oldToken, newToken);

参数

oldToken
DOMString类型,想要替换掉的字符串。
newToken
DOMString类型,表示要将oldToken字符串替换成的字符串。

返回值

boolean类型, 如果oldToken被成功替换,返回 true ,否则返回false

Note: In older browsers, replace() returns void.

Examples

在下面的例子中,我们使用Element.classList方法,将设置在<span> 元素上的class列表检索为DOMTokenList 类型。接着我们替换一个字符串, 并且将新列表写入到 <span> 的内容Node.textContent中。

首先,HTML代码如下:

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

然后是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';
}

输出如下:

规范

Specification Status Comment
DOM
replace()
Living Standard Initial definition

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
replaceChrome Full support 61Edge Full support 17Firefox Full support 49IE No support NoOpera Full support 48Safari Full support 10.1WebView Android Full support 61Chrome Android Full support 61Firefox Android Full support 49Opera Android Full support 45Safari iOS Full support 10.3Samsung Internet Android Full support 8.0
return()'s value is a boolean, not void as it used to be.Chrome Full support 67Edge Full support 18Firefox Full support 61IE No support NoOpera Full support 54Safari Full support 12WebView Android Full support 67Chrome Android Full support 67Firefox Android Full support 61Opera Android Full support 48Safari iOS Full support 12Samsung Internet Android Full support 9.0

Legend

Full support  
Full support
No support  
No support