Javascript DOM HTML Document activeElement Property

Introduction

Get the currently focused element in the document:

var x = document.activeElement.tagName;

Click anywhere in the document to display the active element.

View in separate window

<!DOCTYPE html>
<html>
<body onclick="myFunction()">
<input type="text" value="An input field">
<button>A Button</button>

<p id="demo"></p>

<script>
function myFunction() {//  w  w  w  .j  a  va 2 s  . co m
  var x = document.activeElement.tagName;
  document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

The activeElement property returns the currently focused element in the document.

This property is read-only.

To grab focus, use the element.focus() method.

To find out if the document has focus, use the document.hasFocus() method.




PreviousNext

Related