このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。

View in English Always switch to English

HTMLTextAreaElement: select イベント

Baseline 広く利用可能

この機能は広く実装されており、多くのバージョンの端末やブラウザーで動作します。2015年7月以降、すべてのブラウザーで利用可能です。

select イベントは、テキストが選択されたときに発生します。

構文

このイベント名を addEventListener() などのメソッドで使用するか、イベントハンドラープロパティを設定するかしてください。

js
addEventListener("select", (event) => { })

onselect = (event) => { }

イベント型

一般的な Event です。

選択のログ

html
<textarea>この要素内のテキストを選択してみてください。</textarea>
<p id="log"></p>
js
function logSelection(event) {
  const log = document.getElementById("log");
  const selection = event.target.value.substring(
    event.target.selectionStart,
    event.target.selectionEnd,
  );
  log.textContent = `選択範囲: ${selection}`;
}

const textarea = document.querySelector("textarea");
textarea.addEventListener("select", logSelection);

onselect による同等の処理

イベントハンドラーを onselect プロパティで設定することもできます。

js
textarea.onselect = logSelection;

仕様書

仕様書
HTML
# event-select
HTML
# handler-onselect

ブラウザーの互換性

関連情報