Shadow DOM

W3C Working Draft 22 May 2012

This version
http://www.w3.org/TR/2012/WD-shadow-dom-20120522/
Latest version
http://www.w3.org/TR/shadow-dom/
Latest editor's draft
http://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/shadow/index.html
Previous version
none
Revision history
http://dvcs.w3.org/hg/webcomponents/log/tip/spec/shadow/index.html
Participate
Discuss on public-webapps@w3.org (Web Applications Working Group)
File bugs (w3.org's Bugzilla)
Editor
Dimitri Glazkov, Google, <>

Abstract

This specification describes a method of establishing and maintaining functional boundaries between DOM subtrees and how these subtrees interact with each other within a document tree, thus enabling better functional encapsulation within DOM.

Status of This Document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This document was published by the Web Applications Working Group as a First Public Working Draft. If you wish to make comments regarding this document, please send them to public-webapps@w3.org (subscribe, archives). All feedback is welcome.

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

Table of Contents

  1. 1 About this Document
  2. 2 Dependencies
  3. 3 Terminology
  4. 4 Introduction
    1. 4.1 Functional Encapsulation Example
  5. 5 Shadow DOM Subtrees
    1. 5.1 Upper-boundary Encapsulation
    2. 5.2 Lower-boundary Encapsulation
    3. 5.3 Matching Insertion Points
    4. 5.4 Matching Host and Children, Distributed To Insertion Points
    5. 5.5 Hosting Multiple Shadow Subtrees
    6. 5.6 Nested Shadow Subtrees
    7. 5.7 Rendering Shadow Subtrees
  6. 6 Events
    1. 6.1 Event Retargeting
    2. 6.2 Retargeting relatedTarget
    3. 6.3 Retargeting Focus Events
    4. 6.4 Events that are Always Stopped
    5. 6.5 Event Dispatch
    6. 6.6 Event Retargeting Example
  7. 7 Styles
    1. 7.1 CSS Variables
    2. 7.2 text-decoration Property
  8. 8 User Interaction
    1. 8.1 Ranges and Selections
    2. 8.2 Focus Navigation
    3. 8.3 Active Element
    4. 8.4 Editing
    5. 8.5 Assistive Technology
  9. 9 HTML Elements in Shadow DOM Subtrees
    1. 9.1 Inert HTML Elements
    2. 9.2 HTML Forms
  10. 10 HTML Elements and Their Shadow DOM subtrees
  11. 11 Elements and DOM Objects
    1. 11.1 ShadowRoot Object
      1. 11.1.1 ShadowRoot Attributes
      2. 11.1.2 ShadowRoot Methods
    2. 11.2 The content HTML element
    3. 11.3 The shadow HTML element
  12. 12 Shadow DOM Example
  13. Acknowledgements

1 About this Document

All diagrams, examples, notes, are non-normative, as well as sections explicitly marked as non-normative. Everything else in this specification is normative.

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in the normative parts of this document are to be interpreted as described in RFC2119. For readability, these words do not appear in all uppercase letters in this specification.

To help with layering and to avoid circular dependencies between various parts of specification, this document consists of three consecutive narratives:

  1. setting up the stage for the specification,
  2. explaining of the conceptual model and algorithms behind it, and
  3. expressing this model with DOM interfaces and HTML elements.

In a sense, these parts can be viewed as math, which sets up the reasoning environment, physics, which is the theoretical reasoning about the concept, and mechanics, which is the is the practical application of this reasoning.

Any point, at which a conforming UA must make decisions about the state or reaction to the state of the conceptual model, is captured as algorithm. The algorithms are defined in terms of processing equivalence. The processing equivalence is a constraint imposed on the algorithm implementors, requiring the output of the both UA-implemented and the specified algorithm to be exactly the same for all inputs.

2 Dependencies

This document relies on the following specifications:

3 Terminology

The following terms are used throughout the specification:

DOM
The document object model
document
The Document Object Model's underlying document
node
Any DOM object that participates in a tree
element
A DOM object that implements the Element interface
DOM tree
Any tree, composed of DOM objects
DOM structure
A DOM tree or fragment of a DOM tree

4 Introduction

Web application developers often encounter the need to provide encapsulation of a DOM structure. Despite being part of one document tree, there are typically many functional fragments of DOM (or DOM subtrees), as well as assumptions about these fragments operating independently. This type of encapsulation is called functional encapsulation, as opposed to trust encapsulation, which deals with limiting information flow based on trust and ensuring security of data and state within an application.

Functional encapsulation is primarily concerned with establishing functional boundaries in a document tree. A functional boundary (or just boundary hereon) is a delineation of functional concerns between two loosely coupled units of functionality.

4.1 Functional Encapsulation Example

A Web application user interface is commonly composed of several user interface elements (or widgets), each a DOM subtree. In cases where a widget is tasked with hosting other widgets, the need arises for the widget to understand where its DOM subtree ends and another widget's DOM subtree begins.

This need for observing the functional boundaries in a document tree is even larger when a widget is operated on—added, moved, or removed in the document tree—by an outside actor, such as the Web application that consumes these widgets. Unless the widget consumer knows exactly how a widget's DOM structure is designed, it is impossible for the consumer to reasonably operate on the widget. A typical workaround has been providing alternative means of operation by the widget developer, which, in striving for API consistency quickly extrapolates into a complete set of widget-specific, DOM-like APIs.

5 Shadow DOM Subtrees

To solve this problem at its core, a new abstraction is introduced. The shadow DOM allows multiple DOM subtrees (in addition to the document tree) to be composed into one larger tree when rendered. The existence of multiple DOM subtrees is enabled by letting any element in the document tree to host one or more additional DOM subtrees. These shadow DOM subtrees are governed by a set of rules that establish encapsulation boundaries while retaining the standard DOM composability semantics.

The encapsulation boundaries between shadow DOM subtrees are called shadow boundaries. The elements that host shadow DOM subtrees are called shadow hosts, and the root nodes of the shadow DOM subtrees are called shadow roots.

When rendered, the shadow DOM subtree takes place of the shadow host's content.

To enable composition of shadow host's children and the shadow DOM subtree, a notion of insertion points is added to the abstraction. An insertion point is a defined location in the shadow DOM subtree, to which the shadow host's children are transposed when rendering.

Thus, the encapsulation of a shadow DOM subtree can be viewed as a two-fold problem:

  1. the upper-boundary encapsulation, or governing the boundary between the shadow root and the shadow host; and
  2. the lower-boundary encapsulation, or governing the boundary between the insertion points and the shadow host's children.

5.1 Upper-boundary Encapsulation

To maintain the upper-boundary encapsulation, the following scoping constraints must apply to all nodes in a shadow DOM subtree:

For convenience, the shadow root provides its own set of DOM tree accessor methods. No nodes other than shadow root descendants are accessible with these methods.

The parentNode and parentElement attributes of the shadow root object must always return null.

5.2 Lower-boundary Encapsulation

To maintain the lower-boundary encapsulation, the distribution of child nodes of the shadow host among the insertion points in the associated shadow DOM subtree must have the following traits:

An insertion point may be active or inactive. An active insertion point participates in the distribution process, whereas the inactive insertion does not. If not specifically set to be inactive, the insertion point must be considered active.

If an insertion point is not in a shadow DOM subtree, it must have the same rendering behavior as the HTMLUnknownElement.

The distribution algorithm must produce an outcome that is equivalent of the outcome of processing these steps:

Input
TREE, a shadow DOM subtree
POOL, a list of DOM nodes
Output
The nodes in POOL are distributed among insertion points in TREE.
  1. Repeat for each active insertion point in TREE, in tree order:
    1. Let POINT be the current insertion point
    2. Repeat for each node in POOL:
      1. Let NODE be the current node
      2. If the NODE matches POINT's matching criteria:
        1. Distribute the NODE to POINT
        2. Remove NODE from the POOL
      3. Otherwise, continue to repeat
    3. Continue to repeat

5.3 Matching Insertion Points

The matching criteria for insertion point is defined as a set of selector fragments. Each selector fragment is indeed a fragment in the selector (shadow-host)>(fragment), where (shadow-host) is a selector that uniquely identifies the shadow host, and (fragment) is the selector fragment.

A valid selector fragment may contain:

If any other types of selectors are present in the selector fragment, the fragment must be considered invalid.

A conforming UAs must consider a node as matching a set of selector fragments in the context of a given shadow host, if it:

  1. is a child node of the shadow host; and
  2. all selector fragments in the set are valid; and
  3. child node matches at least one selector fragment in the set or the set is empty.

5.4 Matching Host and Children, Distributed To Insertion Points

Two kinds of selectors, declared in shadow DOM subtrees must match elements outside of the tree in which they are declared:

The :host pseudoclass represents the shadow host of a shadow DOM subtree. If the contextual reference element set is empty or includes elements outside of a shadow DOM subtree, :host matches northing.

Reference combinators match the children of a shadow host, distributed to the insertion points within a shadow DOM subtree. To match, all of these conditions must apply:

For example, .some-insertion-point /select/ div.special will match all div elements that have class attribute set to special and have been distributed to an insertion point that has a class attribute set to some-insertion-point.

All other types of selectors must not cross the shadow boundary from a shadow DOM subtree to the tree of its shadow host.

5.5 Hosting Multiple Shadow Subtrees

A shadow host may host more than one shadow DOM subtree. In such cases, the subtrees are stacked in the order they were added the the host, starting with the subtree added most recently. This set of trees is called a tree stack. The more recently added subtree is called the younger tree, and the less recently added subtree is called the older tree. The most recently added subtree is called the youngest tree.

To facilitate composing multiple shadow subtrees of the same host, a special kind of insertion point is defined. The shadow insertion point designates a place in the shadow DOM subtree, where an older tree is inserted.

Just like other insertion points, the shadow insertion points can be active or inactive.

The composition is performed with the tree composition algorithm, which must be equivalent to processing the following steps:

Input
HOST, a shadow host
Output
All insertion points and shadow insertion points are populated.
  1. Let TREE be the youngest tree in the HOST's tree stack
  2. Let POOL be the list of nodes
  3. Populate POOL with child nodes of the HOST
  4. Repeat while TREE exists:
    1. Let POINT be the first encountered active shadow insertion point in TREE, in tree order
    2. Run the distribution algorithm, supplying POOL and TREE as input
    3. If POINT exists:
      1. Find the next older tree, relative to TREE in the HOST's tree stack
        1. If there is no older tree:
          1. Distribute remaining nodes in POOL, if any, to POINT
          2. stop.
        2. Otherwise:
          1. Set TREE to be this older tree
          2. Assign TREE to the POINT
          3. Continue to repeat
    4. Otherwise, stop.

When an insertion point or a shadow insertion point has nothing assigned or distributed to them, the fallback content must be used instead when rendering. The fallback content is all descendants of the DOM element that represents the insertion point. The insertion points or shadow insertion points in fallback content must be considered inactive.

5.6 Nested Shadow Subtrees

Any element in a shadow DOM subtree can be a shadow host, thus producing nested shadow DOM subtrees. A shadow DOM subtree is nested when its shadow host is itself a part of a shadow DOM subtree.

A shadow DOM subtree is enclosed by another shadow DOM subtree when the enclosing subtree nests the enclosed subtree through one or more levels of nesting.

5.7 Rendering Shadow DOM Subtrees

Rendering of shadow DOM subtrees, or presenting them visually, is defined as a specialization of rendering any DOM subtree, and must happen as these steps:

Input
HOST, a shadow host
Output
Rendering of the HOST, including its shadow DOM subtrees
  1. Run tree composition algorithm for the given shadow host
  2. As content of the shadow host, render the youngest tree as a any DOM subtree, with the following shadow rendering exceptions:

This process of rendering produces a structure that is a composition of several DOM subtrees, including the document tree. The term "as rendered" is used to refer to this structure.

6 Events

When an event is dispatched in a shadow DOM subtree, its path either crosses the shadow boundary or is terminated at the shadow boundary. One exception are the mutation events. The mutation event types must never be dispatched in a shadow DOM subtree.

For event path to cross the shadow boundary, it must be populated with adjusted parents, or nodes that appear as parents as rendered. The parent calculation algorithm is used to determine the adjusted parent of any given node and create the list of ancestors for event dispatch. This algorithm must be equivalent to processing the following steps:

Input
NODE, a DOM node
IGNORE UPPER BOUNDARY, a flag, initialized to false
Output
PARENT, a DOM node's adjusted parent
  1. If NODE is a shadow root:
    1. If NODE is currently assigned to a shadow insertion point:
      1. Let the PARENT be the shadow insertion point to which NODE is assigned to
    2. Otherwise, let the PARENT be the shadow host of the NODE
  2. If NODE is currently distributed to an insertion point in a shadow DOM subtree, and the IGNORE UPPER BOUNDARY flag is set to false
    1. Let the PARENT be the insertion point to which the NODE is distributed to
  3. Otherwise, let PARENT be the node's parent node.

6.1 Event Retargeting

In the cases where events cross the shadow boundaries, the event's information about the target of the event is adjusted in order to maintain upper boundary encapsulation. Event retargeting is a process of computing relative targets for each ancestor of the node at which the event is dispatched. A relative target is a DOM node that most accurately represents the target of a dispatched event at a given ancestor while maintaining the upper boundary encapsulation.

The retargeting algorithm is used to determine relative targets, and it must be equivalent to processing the following steps:

Input
NODE, a DOM node
Output
TARGETS, a list of tuples, each containing NODE's ancestor and its relative target
  1. Let BOUNDARY be a flag, initialized to false
  2. Let STACK be a stack of DOM nodes
  3. Let ANCESTOR be NODE
  4. Repeat while ANCESTOR exists:
    1. If ANCESTOR is a shadow root, set BOUNDARY to true
    2. If ANCESTOR is an insertion point, push ANCESTOR into STACK
    3. If BOUNDARY is set to true
      1. Pop STACK if STACK is not empty
      2. Set BOUNDARY to false state
    4. If STACK is empty, push ANCESTOR into STACK
    5. Let TARGET be the DOM node at the top of STACK
    6. Add (TARGET, ANCESTOR) tuple to TARGETS
    7. Set ANCESTOR to be the result of parent calculation algorithm, given ANCESTOR as input

The retargeting process must occur prior to dispatch of an event.

Some events have a relatedTarget property, which holds a node that's not the event's target, but is related to the event.

For instance, a mouseover event's relatedTarget may hold the node from which the mouse has moved to event's target. In the case where relatedTarget is in a shadow DOM subtree, the conforming UAs must not leak its actual value outside of this subtree. In cases where both relatedTarget and target are part of the same shadow DOM subtree, the conforming UAs must stop events at the shadow boundary to avoid the appearance of spurious mouseover and mouseout events firing from the same node.

Thus, if an event has a relatedTarget, its value and extent of event dispatch must be adjusted. In general:

  1. For a given DOM node, the relatedTarget must be changed to its ancestor (or self) that is in the same shadow DOM subtree as the node
  2. Event listeners must not be invoked on a DOM node for which the target and relatedTarget are the same.

The related target resolution algorithm must be used to determine the value of the relatedTarget property and must be equivalent to processing the following steps:

Input
NODE, the DOM node on which event listeners would be invoked
RELATED, the related target for the event
Output
ADJUSTED, the adjusted related target for NODE
  1. Let CANDIDATES be an empty list
  2. Let ANCESTOR be RELATED
  3. Repeat while ANCESTOR exists:
    1. If a node from the same subtree as ANCESTOR already exists in CANDIDATES, continue
    2. Add ANCESTOR to CANDIDATES
    3. Let ANCESTOR be the result of parent calculation algorithm, given ANCESTOR as input
  4. Let TARGET be NODE
  5. Let ADJUSTED be undefined
  6. Repeat while ADJUSTED is undefined:
    1. If there is a DOM node that is a member of CANDIDATES and is in the same subtree as TARGET, let ADJUSTED be this DOM node
    2. Otherwise:
      1. If TARGET is a shadow root, let TARGET be the shadow host of TARGET
      2. Otherwise, let TARGET be TARGET's parent node

6.3 Retargeting Focus Events

The focus, DOMFocusIn, blur, and DOMFocusOut events must be treated in the same way as events with a relatedTarget, where the corresponding node that is losing focus as a result of target gaining focus or the node that is gaining focus, and thus causing the blurring of target acts as the related target.

6.4 Events that are Always Stopped

The following events must always be stopped at the nearest shadow boundary:

6.5 Event Dispatch

At the time of event dispatch:

Upon completion of the event dispatch, the Event object's target and currentTarget must be to the highest ancestor's relative target. Since it is possible for a script to hold on to the Event object past the scope of event dispatch, this step is necessary to avoid revealing the nodes in shadow DOM subtrees.

6.6 Event Retargeting Example

Suppose we have a user interface for a media controller, represented by this DOM tree, composed of both document and the shadow DOM subtrees. In this example, we will assume that selectors are allowed to cross the shadow boundaries and we will use these selectors to identify the elements. Also, we will invent a fictional shadow-boundary element to demarcate the shadow boundaries:


<div id="player">
    <shadow-boundary>
        <div class="controls">
            <button class="play-button">
            <input type="range" class="timeline">
                <shadow-boundary>
                    <div class="slider-thumb"></div>
                </shadow-boundary>
            </input>
            <div class="volume-slider-container">
                <input type="range" class="volume-slider">
                    <shadow-boundary>
                        <div class="slider-thumb"></div>
                    </shadow-boundary>
                </input>
            </div>
        </div>
    </shadow-boundary>
</div>

Let's have a user position their pointing device over the volume slider's thumb (#player .volume-slider .slider-thumb), thus triggering a mouseover event on that node. For this event, let's pretend it has no associated relatedTarget.

Just before the event is dispatched, we perform retargeting:

  1. We set the relative target of the thumb node to itself.
  2. Walking up, we find a shadow boundary and skip it.
  3. Next up is an input (#player .volume-slider), and we set its relative target to itself, since the previous ancestor was a shadow boundary.
  4. We then walk up to the containing div (#player .volume-slider-container), and use previous ancestor's target -- the input element.
  5. Walking up one more, we reach the controls panel (#player .controls), and again use input element as relative target per retargeting algorithm.
  6. Next, we reach another shadow boundary and skip it.
  7. Finally we walk up to the player element (#player) and set its relative target to itself.

<div id="player"> 7
    <shadow-boundary> 6
        <div class="controls"> 5
            <button class="play-button">
            <input type="range" class="timeline">
                <shadow-boundary>
                    <div class="slider-thumb"></div>
                </shadow-boundary>
            </input>
            <div class="volume-slider-container"> 4
                <input type="range" class="volume-slider"> 3
                    <shadow-boundary> 2
                        <div class="slider-thumb"></div> 1
                    </shadow-boundary>
                </input>
            </div>
        </div>
    </shadow-boundary>
</div>

At the end of this process, we should have the following set of ancestors and relative targets:

Ancestor Relative Target
... div#player
div#player div#player
div#player .controls div#player .controls .volume-slider
div#player .volume-slider-container div#player .controls .volume-slider
div#player .controls .volume-slider div#player .controls .volume-slider
div#player .controls .volume-slider .slider-thumb div#player .controls .volume-slider .slider-thumb

After we dispatch the mouseover event using these newly computed relative targets, the user decides to move their pointing device over the thumb of the timeline (#player .timeline .slider-thumb). This triggers both a mouseout event for the volume slider thumb and the mouseover event for the timeline thumb.

Let's study how the relatedTarget value of the volume thumb's mouseout event is affected and whether event crosses the shadow boundary. For this event, the relatedTarget is the timeline thumb (#player .timeline .slider-thumb).

  1. We find lowest common ancestor of timeline thumb and volume slider thumb: the controls panel (#player .controls).
  2. Walking up, we look for a shadow boundary, and find one just above. This is the lowest common boundary.
  3. Given that the lowest common boundary exists, we limit event dispatch to the descendants of this boundary.
  4. Starting from the lowest common boundary, we walk down the ancestors of the timeline thumb, looking for a shadow boundary. We find it just below the timeline (#player .timeline). This is the first divergent boundary.
  5. We adjust relatedTarget to be the parent of the first divergent boundary, the timeline (#player .timeline). We are now ready to dispatch this event.

<div id="player">
    <shadow-boundary> — lowest common boundary
        <div class="controls">
            <button class="play-button">
            <input type="range" class="timeline">
                <shadow-boundary>  — first divergent boundary
                    <div class="slider-thumb"></div>
                </shadow-boundary>
            </input>
            <div class="volume-slider-container">
                <input type="range" class="volume-slider">
                    <shadow-boundary>
                        <div class="slider-thumb"></div>
                    </shadow-boundary>
                </input>
            </div>
        </div>
    </shadow-boundary>
</div>

7 Styles

To enforce upper-boundary encapsulation, CSS rules declared by the document must not apply in a shadow DOM subtree, unless the apply-author-styles flag is set for this subtree. The flag signals that document CSS rules are applicable in the shadow DOM subtree.

Conversely, to enforce lower-boundary encapsulation, CSS rules declared in a shadow DOM subtree must not apply in the document tree.

The rule applicability algorithm is used to determine whether any given rule is applicable to any DOM tree, and it must be equivalent to processing the following steps:

Input
RULE, a CSS rule whose applicability is being determined
TREE, the document tree or shadow DOM subtree
Output
Whether RULE is applicable in TREE.
  1. If RULE is not an author style, the rule is applicable in TREE.
  2. Otherwise, if TREE is a shadow DOM subtree:
    1. If TREE has apply-author-styles flag set and RULE is declared in the document tree, RULE is applicable in TREE.
    2. Otherwise, if RULE is declared with a style element:
      1. Let STYLE be this style element
      2. If STYLE is in TREE, then RULE is applicable in TREE.
      3. If TREE has apply-author-styles flag set and RULE is declared in an enclosing shadow DOM subtree
        1. Let TOP be this tree
        2. If each shadow DOM subtree that both encloses TREE and is enclosed by TOP has apply-author-styles set, the RULE is applicable in TREE.
    3. Otherwise, RULE is not applicable in TREE.
  3. Otherwise, if TREE is a document tree and RULE is declared in TREE, the rule is applicable in TREE.
  4. Otherwise, RULE is not applicable in TREE.

In a document that contains shadow DOM subtrees, the CSS properties must be inherited from parent nodes, produced using parent calculation algorithm. This requirement has the following effects:

If the reset-style-inheritance flag is set for a shadow DOM subtree, all inheritable CSS properties must behave as if they were explicitly set to the initial value at the upper boundary of the subtree.

7.1 CSS Variables

The shadow host styles being inherited by the children of the shadow root must also apply to CSS Variables. This provides a way for document DOM tree styles to send signals into the shadow DOM subtrees, and for the shadow DOM subtrees to receive these signals with the use of the var() function.

7.2 text-decoration Property

The text decorations, specified by the text-decoration property must not be propagated from shadow hosts to shadow DOM subtrees.

8 User Interaction

8.1 Ranges and Selections

Since a DOM node in a document tree and a DOM node in a shadow DOM subtree never have the same root, there may never exist a valid DOM range that spans either both a document tree and a shadow DOM subtree, or multiple shadow DOM subtrees.

Accordingly, selections may only exist within one tree, because they are defined by a single range. To maintain upper boundary encapsulation, the selection, returned by the window.getSelection() method must never return a selection within a shadow DOM subtree.

The getSelection() method of the shadow root object must return the current selection in this shadow DOM subtree.

8.2 Focus Navigation

Shadow DOM subtrees participate in sequential or directional focus navigation as part of the document tree. The navigation order within the shadow DOM subtrees must be determined using the as-rendered structure and is called shadow DOM navigation order.

For sequential focus navigation, the shadow DOM navigation order sequence must be inserted into the document navigation order:

  1. immediately after the shadow host, if the shadow host is focusable; or
  2. in place of the shadow host as if the shadow host were assigned the value of auto for determining its position.

For directional focus navigation, it is up to the user agent to integrate the shadow DOM navigation order into the document navigation order.

8.3 Active Element

To maintain upper-boundary encapsulation, the value of the Document object's focus API property activeElement must be adjusted. To prevent loss of information when adjusting this value, each shadow root must also have an activeElement property to store the value of the focused element in the shadow DOM subtree.

The active element adjustment algorithm is used to determine the values of the respective activeElement properties, and it must be equivalent to processing the following steps:

Input
ELEMENT, the focused element
Output
Adjusted values of activeElement properties.
  1. Run the retargeting algorithm with ELEMENT as input
  2. For each TUPLE in the resulting list of tuples:
    1. Let ADJUSTED be the first value of the TUPLE
    2. Let NODE be the second value of the TUPLE
    3. If NODE is a Document or a shadow root, set the value of the activeElement to ADJUSTED.

8.4 Editing

The value of the contenteditable attribute must not propagate from shadow host to its shadow DOM subtrees.

8.5 Assistive Technology

User agents with assistive technology traverse the document tree as rendered, and thus enable full use of of WAI-ARIA semantics in the shadow DOM subtrees.

9 HTML Elements in Shadow DOM Subtrees

Comparatively, a shadow DOM subtree can be seen as somewhere between just a DOM subtree in a document and a document fragment. Since it is rendered, a shadow DOM subtree aims to retain the traits of a typical DOM subtree in a document. At the same time, it is an encapsulation abstraction, so it has to avoid affecting the document DOM tree. Thus, the HTML elements must behave as specified in the shadow DOM subtrees, with a few exceptions.

9.1 Inert HTML Elements

A subset of HTML elements must behave as inert, or not part of the document tree. This is consistent how the HTML elements would behave in a document fragment. These elements are:

All other HTML elements in the shadow DOM subtrees must behave as if they were part of the document tree, though scoped to their subtrees.

9.2 HTML Forms

The forms in HTML are scoped at the document level. That is, all form elements and form-associated elements are accessible using the document DOM object's tree accessors. Per scoping constraints, this must exclude elements in the shadow DOM subtrees.

Instead, each shadow DOM subtree must scope its form elements and form-associated elements. Because the form's ownerDocument is the shadow host's document, the form submission must continue to work as specified.

10 HTML Elements and Their Shadow DOM Subtrees

Per specification, some HTML elements are designed to either not render their contents or have special requirements in regard to contents rendering. In order to reconcile these differences in rendering behavior with the shadow DOM tree composition, all HTML elements must have an equivalent of a shadow DOM subtree that is created and populated at the time of element instantiation. It is up to a user agent to define the content of these subtrees. However, all conforming user agents must satisfy the following requirements:

HTML Element Shadow DOM Subtree Requirements
img, iframe, embed, object, video, audio, canvas, map. input, textarea, progress, meter Contains no insertion points
fieldset Contains two insertion points with the following matching criteria:
  1. legend:first-of-type
  2. universal selector
details Contains two insertion points with the following matching criteria:
  1. summary:first-of-type
  2. universal selector
All other elements Contains one insertion point with the universal selector as the matching criteria

11 Elements and DOM Objects

11.1 ShadowRoot Object

The ShadowRoot object represents the shadow root.


[Constructor(in HTMLElement host) raises (DOMException)]
interface ShadowRoot : DocumentFragment {
    HTMLElement getElementById(in DOMString elementId);
    NodeList getElementsByClassName(in DOMString tagName);
    NodeList getElementsByTagName(in DOMString className);
    NodeList getElementsByTagNameNS(DOMString namespace, DOMString localName);
    Selection getSelection();
    attribute bool applyAuthorStyles;
    attribute bool resetStyleInheritance;
    readonly attribute Element activeElement;
    attribute DOMString innerHTML;
}
ShadowRoot implements NodeSelector;

11.1.1 ShadowRoot Attributes

applyAuthorStyles of type bool
Represents the apply-author-styles flag and indicates whether or not the rules in author styles associated with the element's document apply to the shadow DOM subtree. If false (default value), the author styles are not applied to the shadow DOM subtree. If true, the author styles are applied.
On getting, the attribute must return the current value of the apply-author-styles flag for the shadow host's subtree.
On setting, the attribute must set the value of the apply-author-styles flag for the shadow host's subtree to specified value.
resetStyleInheritance of type bool
Represents the reset-style-inheritance flag and indicates whether or not the inheritable CSS properties are set to the initial value at the shadow boundary. If false (default value), the properties continue to inherit. If true, the properties are set to initial value.
On getting, the attribute must return the current value of the reset-style-inheritance flag for the shadow host's subtree.
On setting, the attribute must set the value of the reset-style-inheritance flag for the shadow host's subtree to specified value.
activeElement of type Element, readonly
Represents the currently focused element in the shadow DOM subtree.
On getting, the attribute must return the currently focused element in the shadow DOM subtree or null, if there is none.
innerHTML of type DOMString
represents the markup of ShadowRoot's contents.
On getting, the atribute must return the result of runnig the HTML fragment serialization algorithm with the context object as shadow host.

The nodeType attribute of a ShadowRoot instance must return DOCUMENT_FRAGMENT_NODE. Accordingly, the nodeName attribute of a ShadowRoot instance must return "#document-fragment".

11.1.2 ShadowRoot Methods

constructor
Parameter Type Nullable Optional Description
element Element No No Element that will be the shadow host of the newly created shadow DOM subtree.
Exceptions:
HIERARCHY_REQUEST_ERR
This exception must be thrown when the element parameter is not a valid Element.

When invoked, the ShadowRoot() constructor must run these steps:

  1. Create a new instance of the ShadowRoot object
  2. Establish element, supplied as element argument as the shadow host for the ShadowRoot object
  3. Return ShadowRoot object
getElementById
Must behave exactly like document.getElementById, except scoped to the shadow DOM subtree.
getElementsByClassName
Must behave exactly like document.getElementsByClassName, except scoped to the shadow DOM subtree.
getElementsByTagName
Must behave exactly like document.getElementsByTagName, except scoped to the shadow DOM subtree.
getElementsByTagNameNS
Must behave exactly like document.getElementsByTagNameNS, except scoped to the shadow DOM subtree.
getSelection
Returns the current selection in the shadow DOM subtree.
When invoked, it must return selection in shadow host's subtree.

Invoking the cloneNode() method on a ShadowRoot instance must always throw a DATA_CLONE_ERR exception.

11.2 The content HTML element

The content HTML element represents an insertion point in the shadow DOM subtree.

Context
Where flow content is expected.
Content model
Transparent
Children
Anything as fallback content
Content attributes
Global attributes
select, a set of comma-separated tokens
defines the matching criteria for distributing child nodes of the shadow host. Each token must be a valid selector fragment. If any token is invalid, the entire value of the select attribute is considered invalid.
DOM Interface

interface HTMLContentElement : HTMLElement {
    attribute DOMString select;
}
    
Attributes
select of type DOMString
Must reflect the select attribute.

11.3 The shadow HTML element

The shadow HTML element represents an shadow insertion point in a shadow DOM subtree.

Context
Where flow content is expected.
Content model
Transparent
Children
Anything as fallback content
Content attributes
Global attributes
DOM Interface

interface HTMLShadowElement : HTMLElement {
}
    

12 Shadow DOM Example

Bob was asked to turn a simple list of links into a News Widget, which has links organized into two categories: breaking news and just news. The current document markup for the stories looks like this:


<ul class="stories">
    <li><a href="//example.com/stories/1">A story</a></li>
    <li><a href="//example.com/stories/2">Another story</a></li>
    <li class="breaking"><a href="//example.com/stories/3">Also a story</a></li>
    <li><a href="//example.com/stories/4">Yet another story</a></li>
    <li><a href="//example.com/stories/4">Awesome story</a></li>
    <li class="breaking"><a href="//example.com/stories/5">Horrible story</a></li>
</ul>

To organize the stories, Bob decides to use shadow DOM. Doing so will allow Bob to keep the document markup uncluttered, and harnessing the power of insertion point makes sorting stories by class name a very simple task. After getting another cup of Green Eye, he quickly mocks up the following shadow DOM subtree, to be hosted by the ul element:


<div class="breaking">
    <ul>
        <content select=".breaking"></content> <!-- insertion point for breaking news -->
    </ul>
</div>
<div class="other">
    <ul>
        <content></content> <!-- insertion point for the rest of the news -->
    </ul>
</div>

Bob then styles the newborn widget according to comps from the designer by adding this to the shadow DOM subtree mockup:


<style scoped>
    div.breaking {
        color: Red;
        font-size: 20px;
        border: 1px dashed Purple;
    }
    div.other {
        padding: 2px 0 0 0;
        border: 1px solid Cyan;
    }
</style>

While pondering if his company should start looking for a new designer, Bob converts the mockup to code:


function createStoryGroup(className, contentSelector)
{
    var group = document.createElement('div');
    group.className = className;
    // Empty string in select attribute or absence thereof work the same, so no need for special handling.
    group.innerHTML = '<ul><content select="' + contentSelector + '"></content></ul>';
    return group;
}

function createStyle()
{
    var style = document.createElement('style');
    style.scoped = true;
    style.textContent = 'div.breaking { color: Red;font-size: 20px; border: 1px dashed Purple; }' +
        'div.other { padding: 2px 0 0 0; border: 1px solid Cyan; }';
    return style;
}

function makeShadowSubtree(storyList)
{
    var root = new ShadowRoot(storyList);
    root.appendChild(createStyle());
    root.appendChild(createStoryGroup('breaking', '.breaking'));
    root.appendChild(createStoryGroup('other', ''));
}

document.addEventListener('DOMContentLoaded', function() {
    [].forEach.call(document.querySelectorAll('ul.stories'), makeShadowSubtree);
});

Well done, Bob! With the cup of coffee still half-full, the work is complete. Recognizing his awesomeness, Bob returns to teaching n00bs the ways of WoW.

A few months pass.

It's election time. With Bob at his annual conference, Alice is charged with adding another, temporary box to the news widget, filled with election-related stories. Alice studies Bob's code, reads up on the shadow DOM spec and realizes that, thanks to multiple shadow DOM subtree support, she doesn't have to touch his code. As usual, her solution is elegant and simple, fitting neatly right under Bob's code:


// TODO(alice): BEGIN -- DELETE THIS CODE AFTER ELECTIONS ARE OVER.
var ELECTION_BOX_REMOVAL_DEADLINE = ...;

function createElectionStyle()
{
    var style = document.createElement('style');
    style.scoped = true;
    // TODO(alice): Check designer's desk for hallucinogens.
    style.textContent = 'div.election { color: Magenta;font-size: 24px; border: 2px dotted Fuchsia; }';
    return style;
}

function makeElectionShadowSubtree(storyList)
{
    var root = new ShadowRoot(storyList);
    // Add and style election story box.
    root.appendChild(createElectionStyle());
    root.appendChild(createStoryGroup('election', '.election'));
    // Insert Bob's shadow tree under the election story box.
    root.appendChild(document.createElement('shadow'));
}

if (Date.now() < ELECTION_BOX_REMOVAL_DEADLINE) {
    document.addEventListener('DOMContentLoaded', function() {
        [].forEach.call(document.querySelectorAll('ul.stories'), makeElectionShadowSubtree);
    });
}
// TODO(alice): END -- DELETE THIS CODE AFTER ELECTIONS ARE OVER.

Using the shadow element allows Alice to compose Bob's widget inside of hers—without having to change a line of production code. Smiling to herself, Alice realizes that Bob may have come up with a way to keep the document markup clean, but she is the one who takes the cake for using shadow DOM subtree composition in such a cool way.

Acknowledgements

David Hyatt developed XBL 1.0, and Ian Hickson co-wrote XBL 2.0. These documents provided tremendous insight into the problem of functional encapsulation and greatly influenced this specification.

Alex Russell and his considerable forethought triggered a new wave of enthusiasm around the subject of shadow DOM and how it can be applied practically on the Web.

Dominic Cooney, Hajime Morrita, and Roland Steiner worked tirelessly to scope the problem of functional encapsulation within the confines of the Web platform and provided a solid foundation for this document.

The editor would also like to thank Alex Komoroske, Anne van Kesteren, Brian Kardell, Darin Fisher, Deepak Sherveghar, Edward O'Connor, Elisée Maurer, Erik Arvidsson, Hayato Ito, Jonas Sicking, Malte Ubl, Oliver Nightingale, Olli Pettay, Rafael Weinstein, Sam Dutton, Shinya Kawanaka, and Tab Atkins for their comments and contributions to this specification.

This list is too short. There's a lot of work left to do. Please contribute by reviewing and filing bugs—and don't forget to ask the editor to add your name into this section.