tabindexの初期値について
div
などの通常フォーカスできない要素にJavaScriptでフォーカスを持たせる場合、tabindex="-1"
を指定することがある。
ふと気になってtabindex
のデフォルト値が何なのか調べてみた。
console.log(document.createElement('div').tabIndex); // -1 console.log(document.createElement('a').tabIndex); // 0 console.log(document.createElement('button').tabIndex); // 0
a
やbutton
といったフォーカス可能な要素は0
, それ以外は-1
になるよう。
初期値が-1
であれば指定不要では…?
と思ってtabindex
を指定せずにフォーカスを当ててみようとしたが失敗。
仕様がどうなっているか確認。HTML Living Standardによると、
The tabIndex IDL attribute must reflect the value of the tabindex content attribute. The default value is 0 if the element is an a, area, button, frame, iframe, input, object, select, textarea, or SVG a element, or is a summary element that is a summary for its parent details. The default value is −1 otherwise.
HTML Standard 6.6.3 The tabindex attribute
訳すと以下のような意味になる。
- tabIndexのIDL属性は、 content属性の値を反映する必要がある。
- 以下の要素のIDL属性は初期値が
0
。それ以外は-1
。a
area
button
frame
iframe
input
object
select
textarea
SVG
のa
details
の子要素であるsummary
聞き慣れないIDL
属性、content
属性と言う言葉が出てきた。
ざっくり言うと下記のような意味らしい。
- IDL属性 … JavaScriptのプロパティ。
- content属性 … HTMLで設定した属性。
つまり、JSのtabIndex
プロパティの初期値は0
か-1
で、HTMLに設定したtabindex
の値はJSのプロパティに反映されるということらしい。
そのため、最初に調べたのはtabIndex
プロパティであって、tabindex
属性とは別。
ではHTMLにtabindex
を設定しない場合、属性値は何になるのか。
console.log(document.createElement('div').getAttribute('tabindex')); // null console.log(document.createElement('div').tabIndex); // -1
null
になった。HTMLに設定されたtabindex
はJS側にも反映されるが、未指定の状態では相違が生じるということになる。
まとめると
- HTML属性値とJSプロパティは同一のものに見えるが、実際はそうではない。
- フォーカス可能要素以外にフォーカスを持たせる場合は、やはりHTML側で
tabindex
属性を明示的に指定する必要がある。
余談
また別の話だと思うが、a
のhref
もHTML属性とJSプロパティとで返す値が異なる。
仕様上、HTMLAnchorElement
のhref
属性は絶対URIをを表すと決められている。
<a href="#hoge"></a>
// 表示ページのURLをhttps://example.comとする document.querySelector('a').href; // https://example.com#hoge document.querySelector('a').getAttribute('href'); // #hoge
以上。
参考
- HTML Standard 6.6.3 The tabindex attribute
- HTML 属性リファレンス - HTML: HyperText Markup Language | MDN
- IDL (インタフェース記述言語) - MDN Web Docs 用語集: ウェブ関連用語の定義 | MDN
- HTMLElement.tabIndex - Web API | MDN
- tabindex - HTML: HyperText Markup Language | MDN
- HTMLHyperlinkElementUtils.href - Web API | MDN
- .getAttribute('href')と.hrefの違い
- HTMLAnchorElement.hrefとElement.getAttribute("href")の違い