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';
}
输出看起来像这样:
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. |
实时标准 | 初始定义 |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
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 |
完整支持
不支持
DOMTokenList
AbortController
AbortSignal
AbstractRange
Attr
ByteString
CDATASection
CSSPrimitiveValue
CSSValue
CSSValueList
CharacterData
ChildNode
注释
CustomEvent
DOMConfiguration
DOMError
DOMErrorHandler
DOMException
DOMImplementation
DOMImplementationList
DOMImplementationRegistry
DOMImplementationSource
DOMLocator
DOMObject
DOMParser
DOMPoint
DOMPointInit
DOMPointReadOnly
DOMRect
DOMString
DOMTimeStamp
DOMUserData
Document
DocumentFragment
DocumentType
元素
ElementTraversal
Entity
EntityReference
事件
EventTarget
HTMLCollection
MutationObserver
节点
NodeFilter
NodeIterator
NodeList
NonDocumentTypeChildNode
ProcessingInstruction
PromiseResolver
范围
StaticRange
文本
TextDecoder
TextEncoder
TimeRanges
TreeWalker
TypeInfo
USVString
UserDataHandler
XMLDocument