Document.activeElement - フォーカス中の要素
activeElementは、Documentのプロパティです。フォーカス中の要素を返します。フォーカス中の要素がなければbody要素、それもなければhtml要素、それもなければnullを返します。
概要
- 名前
- activeElement
- 所属
- Document
- IDL
readonly attribute Element? activeElement;
- 仕様書
- https://html.spec.whatwg.org/multipage/interaction.html#dom-document-activeelement
説明
フォーカス中の要素、またはbody要素、またはhtml要素、またはnullを返す。
デモ
Document.activeElementのデモです。フォーカス中の要素を監視しています。
<!-- このコードは編集できます。 -->
<!DOCTYPE html>
<html>
<head>
<style>
input { font-size: 16px ; width: 50% ; }
div#result { white-space: pre-wrap ; }
</style>
</head>
<body>
<p><input></p>
<p><a href="#top" onclick="return false;">リンク</a></p>
<p><button>ボタン</button></p>
<hr>
<div id="result"></div>
<script>
setInterval( function () {
var value = document.activeElement ;
if ( lastValue !== value ) {
document.getElementById( "result" ).innerHTML = "" ;
console.log( value ) ;
document.getElementById( "result" ).appendChild( new Text( value + "\n\n" ) ) ;
if( value.tagName ) document.getElementById( "result" ).appendChild( new Text( value.tagName + "要素" ) ) ;
}
}, 100 ) ;
var lastValue ;
</script>
</body>
</html>
サポート状況
Chrome | Firefox | Safari | Edge | IE | Opera | iOS Safari | Android |
---|---|---|---|---|---|---|---|
● | ● | ● | ● | ● | ● | ● | ● |
関連記事
- Document.getElementsByClassName()
- getElementsByClassName()は、Documentのメソッドです。class属性を指定して要素を取得します。
- ラジオボタンの値を取得する
- どのラジオボタンが選択状態かを取得するには、要素のcheckedプロパティを確認します。
- Document.createNodeIterator()
- createNodeIterator()は、Documentのメソッドです。NodeIteratorを新しく作成します。createNodeIterator()とcreateTreeWalker()は、作成するオブジェクトが違うだけで、仕組みは同じです。
- Document.URL
- URLは、Documentのプロパティです。ドキュメントに関連付けられたURLアドレスを返します。Location.hrefと値は同じです。