javascript エラー「Uncaught DOMException: Failed to execute ‘replace’ on ‘DOMTokenList’: The token provided (‘xxx yyy’) contains HTML space characters, which are not valid in tokens.」の解決方法

javascript エラー「Uncaught DOMException: Failed to execute ‘replace’ on ‘DOMTokenList’: The token provided (‘xxx yyy’) contains HTML space characters, which are not valid in tokens.」の解決方法

javascriptで、エラー「Uncaught DOMException: Failed to execute ‘replace’ on ‘DOMTokenList’: The token provided (‘xxx yyy’) contains HTML space characters, which are not valid in tokens.」が発生した場合の原因と解決方法を記述してます。

環境

  • OS windows11 pro 64bit
  • ブラウザ chrome 104.0.5112.101

エラー内容

以下の、チェックボックスに全てイベントを登録するコードを実行した際に発生。

<div id="sample" class="aaa bbb"></div>

<script>

document.getElementById("sample").classList.replace("aaa bbb", "ccc eee");

</script>

エラーメッセージ

Uncaught DOMException: Failed to execute 'replace' on 'DOMTokenList': The token provided ('aaa bbb') contains HTML space characters, which are not valid in tokens.

画像

firefox102の場合は、以下のエラーが発生します。

Uncaught DOMException: String contains an invalid character

画像

safari15.5では、以下のエラーとなります。

InvalidCharacterError: The string contains invalid characters.

画像

原因

「classList.replace」は、スペースがあるとエラーとなってしまいます。

解決方法

「className.replace」文を使用して、結果を「className」に登録する

<div id="sample" class="aaa bbb"></div>

<script>

let el = document.getElementById("sample")

el.className = el.className.replace("aaa bbb", "ccc eee");

</script>

実行結果