CKTIS / JavaScript
HTMLElement.focus — setting focus programmatically
The focus() method moves focus to an element that can receive it. Learn how focus differs from clicking, how scrolling and focus indication options work, and how to check the result.
Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support
Syntax
element.focus();
element.focus({ preventScroll: true });
element.focus({ preventScroll: true, focusVisible: true });HTMLElement.focus sets focus on an element if it can receive focus; it does not perform a click. It returns undefined, not a success indicator. In a simple document, check the result with document.activeElement === element.
The element must be focusable. tabindex="-1" makes an ordinary element programmatically focusable without adding it to sequential Tab navigation. focus() does not bypass restrictions on disabled elements, elements made inert by inert, or elements not rendered because of display: none.
By default, the method scrolls the element into view; preventScroll: true prevents that scrolling. The browser normally decides whether to display a focus indicator. focusVisible: true requests its display. Do not remove the visible indicator without providing an alternative.
This is an HTML-standard API, not ECMAScript. Basic focus() is supported by current browser engines; check option support separately in target browsers. Node 24 does not establish browser API support. The example deliberately calls the method following a user action.
Examples
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Focus example</title>
<button id="move" type="button">Focus target</button>
<p id="target" tabindex="-1">Target</p>
<pre id="result"></pre>
<script>
const move = document.getElementById('move');
const target = document.getElementById('target');
const result = document.getElementById('result');
move.addEventListener('click', () => {
target.focus({ preventScroll: true });
result.textContent = String(document.activeElement === target);
});
</script>
</html>Result
true
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.