HTMLElement.focus()

The HTMLElement.focus() method sets focus on the specified element, if it can be focused.

Syntax

element.focus()

Examples

Focus on a text field

JavaScript

focusMethod = function getFocus() {           
  document.getElementById("myTextField").focus();
}

HTML

<input type="text" id="myTextField" value="Text field.">
<p></p>
<button type="button" onclick="focusMethod()">Click me to focus on the text field!</button>

Result

Focus on a button

JavaScript

focusMethod = function getFocus() {          
  document.getElementById("myButton").focus();
}

HTML

<button type="button" id="myButton">Click Me!</button>
<p></p>
<button type="button" onclick="focusMethod()">Click me to focus on the button!</button>

Result

Specification

Specification Status Comment
WHATWG HTML Living Standard
The definition of 'focus' in that specification.
Living Standard  
HTML 5.1
The definition of 'focus' in that specification.
Recommendation  
HTML5
The definition of 'focus' in that specification.
Recommendation  
Document Object Model (DOM) Level 2 HTML Specification
The definition of 'focus' in that specification.
Recommendation  
Document Object Model (DOM) Level 1 Specification
The definition of 'focus' in that specification.
Recommendation  

Notes

If you call HTMLElement.focus() from a mousedown event handler, you must call event.preventDefault() to keep the focus from leaving the HTMLElement.

See also

Document Tags and Contributors

 Last updated by: xrtariq2594,