2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

HTMLのLABEL要素を.focus()でフォーカスしたかった

Last updated at Posted at 2019-06-21

tabindex="0"を設定した<label>.focus()してもフォーカスされない。調べてもクリティカルな回答がない…。から試行錯誤で至ったコードを晒します。

状況

See the Pen Toggle-Button by horyu (@horyu) on CodePen.

見て読んでお分かりのように、こんな感じでトグルボタン用の<label>がありました。隣の<button>label.focus() が仕組んであります。document.activeElement ===の後ろの<span>に現在フォーカスされているエレメントが表示されるようになっています。さて、ボタンをクリックしてみましょう。

・・・

**できるじゃん!!!!となった方、そのブラウザは良いですね。私が常用するWaterfox**では出来ませんでした。

実装

Waterfox 56.2.11 (64 ビット)でlabelをフォーカスさせる例が以下となります。

See the Pen Toggle-Button Focus by horyu (@horyu) on CodePen.

フォーカスの実装は以下のようになりました。

// 参考:
// https://stackoverflow.com/questions/2388164/set-focus-on-div-contenteditable-element#answer-16863913
const setFocus = (label) => {
  label.setAttribute('contentEditable', true);
  const range = document.createRange();
  range.setStart(label, 0);
  range.setEnd(label, 0);
  const sel = window.getSelection();
  sel.removeAllRanges();
  sel.addRange(range);
  label.setAttribute('contentEditable', false);
};

概説としてはこんな感じになります。

  1. labelcontentEditable属性をtrueにし、テキストを選択可能にする
  2. labelのみを含むRangeオブジェクトを作る
  3. ユーザーの選択範囲Selectionオブジェクトの中身を作りたてのRange`オブジェクトだけにする
  4. labelcontentEditable属性をfalseにする
2
1
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?