HTMLElement

HTMLElement.prototype.focus

Sets focus on the specified element if it can be focused

Syntax

JavaScript
element.focus(options?)

Parameters

ParameterTypeDescription
optionsFocusOptionsOptional object with preventScroll boolean property

Return Value

undefined

Examples

Basic Usage
const input = document.querySelector<HTMLInputElement>('#search')!
input.focus()
Practical Example
function focusFirstInvalid(form: HTMLFormElement) {
  const invalid = form.querySelector(':invalid') as HTMLElement | null
  invalid?.focus({ preventScroll: false })
}
Advanced Usage
const modal = document.querySelector('.modal') as HTMLElement
modal.focus({ preventScroll: true })

Understanding HTMLElement.prototype.focus

The HTMLElement.prototype.focus method in JavaScript sets focus on the specified element if it can be focused. It belongs to the HTMLElement object and is one of the most widely used methods for working with htmlelement values in modern JavaScript and TypeScript applications.

The method signature is element.focus(options?). It accepts 1 parameter: options. When called, it returns undefined. Understanding when and how to use focus() helps you write more expressive, readable code.

Common use cases for HTMLElement.prototype.focus include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like dom-blur, dom-click, enabling you to chain operations together for complex data manipulation pipelines.

Browser support for HTMLElement.prototype.focus is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.

Browser Compatibility

Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.

Related Methods

More HTMLElement Methods

Other methods in the HTMLElement object

Related Tools

More HTMLElement Methods

Explore JavaScript Methods

Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.