Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / HTML

shadowrootdelegatesfocus — focus delegation in declarative Shadow DOM

The boolean shadowrootdelegatesfocus attribute on template enables focus delegation for a declaratively created shadow root. It allows focus to move from the host to a suitable internal element; it neither creates a shadow root by itself nor automatically focuses anything.

Version: WHATWG HTML Living Standard; index snapshot date recorded separately

Syntax

<template shadowrootmode="open" shadowrootdelegatesfocus>…</template>

shadowrootdelegatesfocus is a boolean attribute on template. When a declarative shadow root is created, its presence enables focus delegation, while its absence disables it. A valid shadowrootmode, either open or closed, is also needed. This attribute alone does not create a shadow root.

When the host receives a focus request, for example through host.focus(), the browser can forward focus to a suitable element in its shadow tree. In the example, the input is the only such element. The attribute does not behave like autofocus: its presence does not focus anything when the page loads.

Valid forms include shadowrootdelegatesfocus, shadowrootdelegatesfocus="", and shadowrootdelegatesfocus="shadowrootdelegatesfocus". The value "false" is not a valid boolean-attribute value and does not disable the feature: the present attribute still enables it. To create a root without focus delegation, omit the attribute from the declaration.

The option is read when the parser creates the root, not as a live setting on an existing root. In the example, open permits access through host.shadowRoot. After clicking Run, document.activeElement identifies the host, while root.activeElement identifies the internal input; both comparisons produce true.

Examples

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Focus delegation</title>
<div id="host">
  <template shadowrootmode="open" shadowrootdelegatesfocus>
    <label>Name <input id="name" type="text"></label>
  </template>
</div>
<button id="run" type="button">Run</button>
<pre id="result"></pre>
<script>
  const host = document.getElementById('host');
  document.getElementById('run').addEventListener('click', () => {
    host.focus();
    const root = host.shadowRoot;
    document.getElementById('result').textContent = [
      document.activeElement === host,
      root.activeElement === root.getElementById('name')
    ].join('\n');
  });
</script>
</html>

Result

true
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.

Sources