DOMTokenList: replace() method
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2018.
Thereplace() method of theDOMTokenList interfacereplaces an existing token with a new token.If the first token doesn't exist,replace() returnsfalse immediately,without adding the new token to the token list.
In this article
Syntax
replace(oldToken, newToken)Parameters
Return value
A boolean value, which istrue ifoldToken wassuccessfully replaced, orfalse if not.
Examples
In the following example we retrieve the list of classes set on a<span> element as aDOMTokenList usingElement.classList. We then replace a token in the list, and write thelist into the<span>'sNode.textContent.
First, the HTML:
<span></span>Now the #"span");const classes = span.classList;const result = classes.replace("c", "z");span.textContent = result ? classes : "token not replaced successfully";
The output looks like this:
Specifications
| Specification |
|---|
| DOM> # ref-for-dom-domtokenlist-replace①> |