javascript aria-labelから要素を取得する

javascript aria-labelから要素を取得する

javascriptで、aria-labelから要素を取得するサンプルコードを記述してます。

環境

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

aria-labelから要素を取得

aria-labelから要素を取得するには、「querySelector」か「querySelectorAll」を使用します。

<button aria-label="ヘルプ">?</button>
<button aria-label="ヘルプ">?</button>

<script>

const elm = document.querySelector('[aria-label="ヘルプ"]');
console.log(elm);

const elms = document.querySelectorAll('[aria-label="ヘルプ"]');
console.log(elms);

</script>

実行結果を見ると、取得されていることが確認できます。

サンプルコード

以下は、
「aria-label」があるボタンから要素を取得して、クリックでテキストを変更する
サンプルコードとなります。

※cssには「bootstrap material」を使用してます。関数はアロー関数で記述してます。

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

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <!-- MDB -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/4.2.0/mdb.min.css" rel="stylesheet" />
</head>

<body>
  <div class="container text-center w-25" style="margin-top:150px">

    <button id="btn" aria-label="ヘルプ" type="button" class="btn mt-1 btn-danger">
      ?
    </button>

  </div>

  <script>

    const elm = document.querySelector('[aria-label="ヘルプ"]');

    // クリックイベントを登録
    elm.onclick = () => {

      elm.textContent = "button";

    };

  </script>
</body>

</html>

変更されていることが確認できます。