javascript classList.replaceを使用してクラスを入れ替える

javascript classList.replaceを使用してクラスを入れ替える

javascriptで、classList.replaceを使用して、クラスを入れ替えるサンプルコードを掲載してます。ブラウザはchromeを使用しています。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 103.0.5060.134

classList.replace使い方

「classList.replace」を使用することで、以下のように「class」を入れ替えることが可能です。

<div id="hoge" class="foo"></div>

<script>

'use strict';

document.getElementById("hoge").classList.replace("foo", "bar");

</script>

実行結果

存在しないクラス名を指定すると、エラーにはならず、falseが返ります。

'use strict';

console.log( document.getElementById("hoge").classList.replace("noclass", "bar") );
// false

既に存在するクラスに置換

既に存在するクラスに置換しようとした場合は、置換対象が消えるだけで複数は作成されません。

<div id="hoge" class="foo"></div>

<script>

'use strict';

document.getElementById("hoge").classList.replace("foo", "bar");

</script>

実行結果

スペースを含んで置換

また、以下のようにスペースを含んでクラス名を指定するとエラーが発生します。

<div id="hoge" class="foo hoge"></div>

<script>

'use strict';

document.getElementById("hoge").classList.replace("foo hoge", "bar");

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

</script>

複数のクラスを変更したい場合は「className.replace」を使用して「className」に代入します。

<div id="hoge" class="foo hoge"></div>

<script>

'use strict';

let el = document.getElementById("hoge")

el.className = el.className.replace("foo hoge", "bar");

</script>

実行結果

classList.replace小ネタ

‘use strict’だとエラーになりますが、以下のように配列でメソッドにアクセスすることも可能です。

document.getElementById("hoge")[x='classList'][y='replace']("foo", "bar");

一度定義すると、以下のように変数として利用できます。

document.getElementById("hoge")[x][y]("bar", "hoge");

ちなみに、「’use strict’」を使用すると「not defined」となります。

'use strict';

document.getElementById("hoge")[x='classList'][y='replace']("foo", "bar");

// Uncaught ReferenceError: x is not defined

サンプルコード

以下は、
「実行」ボタンをクリックすると、指定した要素のクラスを入れ替えて、表示する
サンプルコードとなります。

※cssには「tailwind」を使用して、アロー関数で関数は定義してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet">
</head>

<script>

  const hoge = () => {

    // 要素を変更
    result.classList.replace("bg-pink-700", "bg-blue-700");

  }

  window.onload = () => {
    // クリックイベントを登録
    btn.onclick = () => { hoge(); }; // document.getElementById('btn');を省略    
  }

</script>

<body>
  <div class="container mx-auto my-56 w-56 px-4">

    <div class="flex justify-center">
      <p id="result" class="bg-pink-700 text-white py-4 px-8 rounded-full mb-3 mt-4">変更する要素</p>
    </div>

    <div class="flex justify-center">
      <button id="btn" type="button"
        class="mt-5 bg-transparent border border-yellow-500 hover:border-yellow-300 text-yellow-500 hover:text-yellow-300 font-bold py-2 px-4 rounded-full">
        実行
      </button>
    </div>
  </div>

</body>

</html>

要素のクラスが、変更されていることが確認できます。