1. Infrastructure
This specification depends on the Infra Standard. [INFRA]
Some of the terms used in this specification are defined in Encoding, Selectors, Web IDL, XML, and Namespaces in XML. [ENCODING] [SELECTORS4] [WEBIDL] [XML] [XML-NAMES]
The term context object is an alias for this.
Usage of context object is deprecated in favor of this.
When extensions are needed, the DOM Standard can be updated accordingly, or a new standard can be written that hooks into the provided extensibility hooks for applicable specifications.
1.1. Trees
A tree is a finite hierarchical tree structure. In tree order is preorder, depth-first traversal of a tree.
An object that participates in a tree has a parent, which is either null or an object, and has children, which is an ordered set of objects. An object A whose parent is object B is a child of B.
The root of an object is itself, if its parent is null, or else it is the root of its parent. The root of a tree is any object participating in that tree whose parent is null.
An object A is called a descendant of an object B, if either A is a child of B or A is a child of an object C that is a descendant of B.
An inclusive descendant is an object or one of its descendants.
An object A is called an ancestor of an object B if and only if B is a descendant of A.
An inclusive ancestor is an object or one of its ancestors.
An object A is called a sibling of an object B, if and only if B and A share the same non-null parent.
An inclusive sibling is an object or one of its siblings.
An object A is preceding an object B if A and B are in the same tree and A comes before B in tree order.
An object A is following an object B if A and B are in the same tree and A comes after B in tree order.
The first child of an object is its first child or null if it has no children.
The last child of an object is its last child or null if it has no children.
The previous sibling of an object is its first preceding sibling or null if it has no preceding sibling.
The next sibling of an object is its first following sibling or null if it has no following sibling.
The index of an object is its number of preceding siblings, or 0 if it has none.
1.2. Ordered sets
The ordered set parser takes a string input and then runs these steps:
-
Let inputTokens be the result of splitting input on ASCII whitespace.
-
Let tokens be a new ordered set.
- Return tokens.
The ordered set serializer takes a set and returns the concatenation of set using U+0020 SPACE.
1.3. Selectors
To scope-match a selectors string selectors against a node, run these steps:
-
Let s be the result of parse a selector selectors. [SELECTORS4]
-
If s is failure, then throw a "
SyntaxError
"DOMException
. -
Return the result of match a selector against a tree with s and node’s root using scoping root node. [SELECTORS4].
Support for namespaces within selectors is not planned and will not be added.
1.4. Namespaces
To validate a qualifiedName, throw an
"InvalidCharacterError
" DOMException
if qualifiedName does not match
the Name
or QName
production.
To validate and extract a namespace and qualifiedName, run these steps:
- If namespace is the empty string, set it to null.
- Validate qualifiedName.
- Let prefix be null.
- Let localName be qualifiedName.
- If qualifiedName contains a "
:
" (U+003E), then split the string on it and set prefix to the part before and localName to the part after. - If prefix is non-null and namespace is null, then throw a
"
NamespaceError
"DOMException
. - If prefix is "
xml
" and namespace is not the XML namespace, then throw a "NamespaceError
"DOMException
. - If either qualifiedName or prefix is
"
xmlns
" and namespace is not the XMLNS namespace, then throw a "NamespaceError
"DOMException
. - If namespace is the XMLNS namespace and neither qualifiedName nor prefix is "
xmlns
", then throw a "NamespaceError
"DOMException
. - Return namespace, prefix, and localName.
2. Events
2.1. Introduction to "DOM Events"
Throughout the web platform events are dispatched to objects to signal an
occurrence, such as network activity or user interaction. These objects implement the EventTarget
interface and can therefore add event listeners to observe events by calling addEventListener()
:
obj. addEventListener( "load" , imgFetched) function imgFetched( ev) { // great success …}
Event listeners can be removed
by utilizing the removeEventListener()
method passing the same arguments.
Alternatively, event listeners can be removed by passing an AbortSignal
to addEventListener()
and calling abort()
on the controller
owning the signal.
Events are objects too and implement the Event
interface (or a derived interface). In the example above ev is the event. ev is
passed as an argument to the event listener’s callback (typically a JavaScript Function as shown above). Event listeners key off the event’s type
attribute value
("load
" in the above example). The event’s target
attribute value returns the
object to which the event was dispatched (obj above).
Although events are typically dispatched by the user agent as the result of user interaction or the completion of some task, applications can dispatch events themselves by using what are commonly known as synthetic events:
// add an appropriate event listener obj. addEventListener( "cat" , function ( e) { process( e. detail) }) // create and dispatch the event var event= new CustomEvent( "cat" , { "detail" : { "hazcheeseburger" : true }}) obj. dispatchEvent( event)
Apart from signaling, events are
sometimes also used to let an application control what happens next in an
operation. For instance as part of form submission an event whose type
attribute value is
"submit
" is dispatched. If this event’s preventDefault()
method is
invoked, form submission will be terminated. Applications who wish to make
use of this functionality through events dispatched by the application
(synthetic events) can make use of the return value of the dispatchEvent()
method:
if ( obj. dispatchEvent( event)) { // event was not canceled, time for some magic …}
When an event is dispatched to an object that participates in a tree (e.g., an element), it can reach event listeners on that object’s ancestors too. Effectively, all the object’s inclusive ancestor event listeners whose capture is true are invoked, in tree order. And then, if event’s bubbles
is true, all the object’s inclusive ancestor event listeners whose capture is false are invoked, now in
reverse tree order.
Let’s look at an example of how events work in a tree:
<!doctype html> < html > < head > < title > Boring example</ title > </ head > < body > < p > Hello< span id = x > world</ span > !</ p > < script > function test( e) { debug( e. target, e. currentTarget, e. eventPhase) } document. addEventListener( "hey" , test, { capture: true }) document. body. addEventListener( "hey" , test) var ev= new Event( "hey" , { bubbles: true }) document. getElementById( "x" ). dispatchEvent( ev) </ script > </ body > </ html >
The debug
function will be invoked twice. Each time the event’s target
attribute value will be the span
element. The first time currentTarget
attribute’s value will be the document, the second time the body
element. eventPhase
attribute’s value switches from CAPTURING_PHASE
to BUBBLING_PHASE
. If an event listener was registered
for the span
element, eventPhase
attribute’s value would have
been AT_TARGET
.
2.2. Interface Event
In all current engines.
Opera4+Edge79+
Edge (Legacy)12+IE6+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
Node.js14.5.0+
In all current engines.
Opera11.6+Edge79+
Edge (Legacy)12+IENone
Firefox for Android14+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile12+
Node.js15.0.0+
[Exposed =(Window ,Worker ,AudioWorklet )]interface {
Event (
constructor DOMString ,
type optional EventInit = {});
eventInitDict readonly attribute DOMString type ;readonly attribute EventTarget ?target ;readonly attribute EventTarget ?srcElement ; // legacyreadonly attribute EventTarget ?currentTarget ;sequence <EventTarget >composedPath ();const unsigned short NONE = 0;const unsigned short CAPTURING_PHASE = 1;const unsigned short AT_TARGET = 2;const unsigned short BUBBLING_PHASE = 3;readonly attribute unsigned short eventPhase ;undefined stopPropagation ();attribute boolean cancelBubble ; // legacy alias of .stopPropagation()undefined stopImmediatePropagation ();readonly attribute boolean bubbles ;readonly attribute boolean cancelable ;attribute boolean returnValue ; // legacyundefined preventDefault ();readonly attribute boolean defaultPrevented ;readonly attribute boolean composed ; [LegacyUnforgeable ]readonly attribute boolean isTrusted ;readonly attribute DOMHighResTimeStamp timeStamp ;undefined initEvent (DOMString ,
type optional boolean =
bubbles false ,optional boolean =
cancelable false ); // legacy };dictionary {
EventInit boolean =
bubbles false ;boolean =
cancelable false ;boolean =
composed false ; };
An Event
object is simply named an event. It allows for
signaling that something has occurred, e.g., that an image has completed downloading.
A potential event target is null or an EventTarget
object.
An event has an associated target (a potential event target). Unless stated otherwise it is null.
An event has an associated relatedTarget (a potential event target). Unless stated otherwise it is null.
Other specifications use relatedTarget to define a relatedTarget
attribute. [UIEVENTS]
An event has an associated touch target list (a list of zero or more potential event targets). Unless stated otherwise it is the empty list.
The touch target list is for the exclusive use of defining the TouchEvent
interface and related interfaces. [TOUCH-EVENTS]
An event has an associated path. A path is a list of structs. Each struct consists of an invocation target (an EventTarget
object), an invocation-target-in-shadow-tree (a boolean), a shadow-adjusted target (a potential event target), a relatedTarget (a potential event target), a touch target list (a list of potential event targets), a root-of-closed-tree (a boolean), and
a slot-in-closed-tree (a boolean). A path is initially
the empty list.
event = new Event(type [, eventInitDict])
- Returns a new event whose
type
attribute value is set to type. The eventInitDict argument allows for setting thebubbles
andcancelable
attributes via object members of the same name. event .
type
- Returns the type of event, e.g.
"
click
", "hashchange
", or "submit
". event .
target
- Returns the object to which event is dispatched (its target).
event .
currentTarget
- Returns the object whose event listener’s callback is currently being invoked.
event .
composedPath()
- Returns the invocation target objects of event’s path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root’s mode is "
closed
" that are not reachable from event’scurrentTarget
. event .
eventPhase
- Returns the event’s phase, which is one of
NONE
,CAPTURING_PHASE
,AT_TARGET
, andBUBBLING_PHASE
. event . stopPropagation()
- When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object.
event . stopImmediatePropagation()
- Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects.
event .
bubbles
- Returns true or false depending on how event was initialized. True if event goes through its target’s ancestors in reverse tree order, and false otherwise.
event .
cancelable
- Returns true or false depending on how event was initialized. Its return
value does not always carry meaning, but true can indicate that part of the operation
during which event was dispatched, can be canceled by invoking the
preventDefault()
method. event . preventDefault()
- If invoked when the
cancelable
attribute value is true, and while executing a listener for the event withpassive
set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. event .
defaultPrevented
- Returns true if
preventDefault()
was invoked successfully to indicate cancelation, and false otherwise. event .
composed
- Returns true or false depending on how event was initialized. True if event invokes listeners past a
ShadowRoot
node that is the root of its target, and false otherwise. event .
isTrusted
- Returns true if event was dispatched by the user agent, and false otherwise.
event .
timeStamp
- Returns the event’s timestamp as the number of milliseconds measured relative to the time origin.
In all current engines.
Opera7+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
Node.js14.5.0+
The type
attribute must return the value it was
initialized to. When an event is created the attribute must be initialized to the empty
string.
In all current engines.
Opera7+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
Node.js14.5.0+
The target
attribute’s getter, when invoked, must
return this’s target.
The srcElement
attribute’s getter, when invoked, must
return this’s target.
In all current engines.
Opera7+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari10+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
Node.js14.5.0+
The currentTarget
attribute must return the value it
was initialized to. When an event is created the attribute must be initialized to null.
In all current engines.
Opera40+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android52+iOS Safari10+Chrome for Android53+Android WebView53+Samsung Internet6.0+Opera Mobile41+
Node.js14.5.0+
The composedPath()
method, when invoked, must run these
steps:
-
Let composedPath be an empty list.
-
If path is empty, then return composedPath.
-
Let currentTarget be this’s
currentTarget
attribute value. -
Append currentTarget to composedPath.
-
Let currentTargetIndex be 0.
-
Let currentTargetHiddenSubtreeLevel be 0.
-
Let index be path’s size − 1.
-
While index is greater than or equal to 0:
-
If path[index]'s root-of-closed-tree is true, then increase currentTargetHiddenSubtreeLevel by 1.
-
If path[index]'s invocation target is currentTarget, then set currentTargetIndex to index and break.
-
If path[index]'s slot-in-closed-tree is true, then decrease currentTargetHiddenSubtreeLevel by 1.
-
Decrease index by 1.
-
-
Let currentHiddenLevel and maxHiddenLevel be currentTargetHiddenSubtreeLevel.
-
Set index to currentTargetIndex − 1.
-
While index is greater than or equal to 0:
-
If path[index]'s root-of-closed-tree is true, then increase currentHiddenLevel by 1.
-
If currentHiddenLevel is less than or equal to maxHiddenLevel, then prepend path[index]'s invocation target to composedPath.
-
If path[index]'s slot-in-closed-tree is true, then:
-
Decrease currentHiddenLevel by 1.
-
If currentHiddenLevel is less than maxHiddenLevel, then set maxHiddenLevel to currentHiddenLevel.
-
-
Decrease index by 1.
-
-
Set currentHiddenLevel and maxHiddenLevel to currentTargetHiddenSubtreeLevel.
-
Set index to currentTargetIndex + 1.
-
While index is less than path’s size:
-
If path[index]'s slot-in-closed-tree is true, then increase currentHiddenLevel by 1.
-
If currentHiddenLevel is less than or equal to maxHiddenLevel, then append path[index]'s invocation target to composedPath.
-
If path[index]'s root-of-closed-tree is true, then:
-
Decrease currentHiddenLevel by 1.
-
If currentHiddenLevel is less than maxHiddenLevel, then set maxHiddenLevel to currentHiddenLevel.
-
-
Increase index by 1.
-
-
Return composedPath.
In all current engines.
Opera32+Edge79+
Edge (Legacy)12+IE9+
Firefox for AndroidYesiOS SafariYesChrome for Android45+Android WebView45+Samsung Internet5.0+Opera Mobile32+
Node.js14.5.0+
The eventPhase
attribute must return the value it was
initialized to, which must be one of the following:
NONE
(numeric value 0)- Events not currently dispatched are in this phase.
CAPTURING_PHASE
(numeric value 1)- When an event is dispatched to an object that participates in a tree it will be in this phase before it reaches its target.
AT_TARGET
(numeric value 2)- When an event is dispatched it will be in this phase on its target.
BUBBLING_PHASE
(numeric value 3)- When an event is dispatched to an object that participates in a tree it will be in this phase after it reaches its target.
Initially the attribute must be initialized to NONE
.
Each event has the following associated flags that are all initially unset:
- stop propagation flag
- stop immediate propagation flag
- canceled flag
- in passive listener flag
- composed flag
- initialized flag
- dispatch flag
In all current engines.
Opera7+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
Node.js14.5.0+
The stopPropagation()
method, when invoked, must set this’s stop propagation flag.
In all current engines.
OperaYesEdgeYes
Edge (Legacy)12+IEYes
Firefox for Android53+iOS SafariYesChrome for AndroidYesAndroid WebViewYesSamsung InternetYesOpera MobileYes
Node.js14.5.0+
The cancelBubble
attribute’s getter, when invoked,
must return true if this’s stop propagation flag is set, and false otherwise.
The cancelBubble
attribute’s setter, when invoked, must set this’s stop propagation flag if the given value is true, and do nothing otherwise.
Event/stopImmediatePropagation
In all current engines.
Opera15+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android10+iOS Safari5+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+
Node.js14.5.0+
The stopImmediatePropagation()
method, when invoked,
must set this’s stop propagation flag and this’s stop immediate propagation flag.
In all current engines.
OperaYesEdgeYes
Edge (Legacy)12+IE?
Firefox for AndroidYesiOS SafariYesChrome for AndroidYesAndroid WebViewYesSamsung InternetYesOpera MobileYes
Node.js14.5.0+
In all current engines.
OperaYesEdgeYes
Edge (Legacy)12+IE?
Firefox for AndroidYesiOS SafariYesChrome for AndroidYesAndroid WebViewYesSamsung InternetYesOpera MobileYes
Node.js14.5.0+
The bubbles
and cancelable
attributes must return the values they were
initialized to.
To set the canceled flag, given an event event, if event’s cancelable
attribute value is true and event’s in passive listener flag is unset, then set event’s canceled flag, and do
nothing otherwise.
The returnValue
attribute’s getter, when invoked,
must return false if this’s canceled flag is set, and true otherwise.
The returnValue
attribute’s setter, when invoked, must set the canceled flag with this if the given value is false, and do nothing otherwise.
In all current engines.
Opera7+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
Node.js14.5.0+
The preventDefault()
method, when invoked, must set the canceled flag with this.
There are scenarios where invoking preventDefault()
has no
effect. User agents are encouraged to log the precise cause in a developer console, to aid
debugging.
In all current engines.
Opera11+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android6+iOS Safari5+Chrome for Android18+Android WebViewYesSamsung Internet1.0+Opera Mobile11+
Node.js14.5.0+
The defaultPrevented
attribute’s getter, when
invoked, must return true if this’s canceled flag is set, and false otherwise.
In all current engines.
Opera40+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android52+iOS SafariYesChrome for Android53+Android WebView53+Samsung Internet6.0+Opera Mobile41+
Node.js14.5.0+
The composed
attribute’s getter, when invoked, must
return true if this’s composed flag is set, and false otherwise.
In all current engines.
Opera33+Edge79+
Edge (Legacy)12+IENone
Firefox for AndroidYesiOS Safari10+Chrome for Android46+Android WebView46+Samsung Internet5.0+Opera Mobile33+
Node.js14.5.0+
The isTrusted
attribute must return the value it was
initialized to. When an event is created the attribute must be initialized to false.
isTrusted
is a convenience that indicates whether an event is dispatched by the user agent (as opposed to using dispatchEvent()
). The sole legacy exception is click()
, which causes
the user agent to dispatch an event whose isTrusted
attribute is initialized to
false.
In all current engines.
Opera36+Edge79+
Edge (Legacy)12+IEYes
Firefox for AndroidYesiOS SafariYesChrome for Android49+Android WebView49+Samsung Internet5.0+Opera Mobile36+
Node.js14.5.0+
The timeStamp
attribute must return the value it was
initialized to.
To initialize an event, with type, bubbles, and cancelable, run these steps:
-
Set event’s initialized flag.
-
Unset event’s stop propagation flag, stop immediate propagation flag, and canceled flag.
-
Set event’s
isTrusted
attribute to false. -
Set event’s target to null.
-
Set event’s
type
attribute to type. -
Set event’s
bubbles
attribute to bubbles. -
Set event’s
cancelable
attribute to cancelable.
The initEvent(type, bubbles, cancelable)
method, when invoked, must run these steps:
-
If this’s dispatch flag is set, then return.
-
Initialize this with type, bubbles, and cancelable.
initEvent()
is redundant with event constructors and
incapable of setting composed
. It has to be supported for legacy content.
2.3. Legacy extensions to the Window
interface
partial interface Window { [Replaceable ]readonly attribute (Event or undefined )event ; // legacy };
Each Window
object has an associated current event (undefined or an Event
object). Unless stated otherwise it is undefined.
In all current engines.
Opera7+Edge79+
Edge (Legacy)12+IE4+
Firefox for Android66+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
The event
attribute’s getter, when invoked, must
return this’s current event.
Web developers are strongly encouraged to instead rely on the Event
object passed
to event listeners, as that will result in more portable code. This attribute is not available in
workers or worklets, and is inaccurate for events dispatched in shadow trees.
2.4. Interface CustomEvent
In all current engines.
Opera11+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android6+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile11+
In all current engines.
Opera11.6+Edge79+
Edge (Legacy)18IENone
Firefox for Android14+iOS Safari6.1+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile12+
[Exposed =(Window ,Worker )]interface :
CustomEvent Event {(
constructor DOMString ,
type optional CustomEventInit = {});
eventInitDict readonly attribute any detail ;undefined initCustomEvent (DOMString ,
type optional boolean =
bubbles false ,optional boolean =
cancelable false ,optional any =
detail null ); // legacy };dictionary :
CustomEventInit EventInit {any =
detail null ; };
Events using the CustomEvent
interface can be used to carry custom data.
event = new CustomEvent(type [, eventInitDict])
- Works analogously to the constructor for
Event
except that the eventInitDict argument now allows for setting thedetail
attribute too. event .
detail
- Returns any custom data event was created with. Typically used for synthetic events.
In all current engines.
Opera11.6+Edge79+
Edge (Legacy)14+IENone
Firefox for Android14+iOS Safari6.1+Chrome for AndroidYesAndroid WebViewYesSamsung InternetYesOpera MobileYes
The detail
attribute must return the value it
was initialized to.
The initCustomEvent(type, bubbles, cancelable, detail)
method must, when invoked, run these steps:
-
If this’s dispatch flag is set, then return.
-
Initialize this with type, bubbles, and cancelable.
2.5. Constructing events
Specifications may define event constructing steps for all or some events. The algorithm is passed an event as indicated in the inner event creation steps.
This construct can be used by Event
subclasses that have a more complex structure
than a simple 1:1 mapping between their initializing dictionary members and IDL attributes.
When a constructor of the Event
interface, or of an interface that inherits from the Event
interface, is invoked, these steps
must be run, given the arguments type and eventInitDict:
-
Let event be the result of running the inner event creation steps with this interface, null, now, and eventInitDict.
-
Initialize event’s
type
attribute to type. -
Return event.
To create an event using eventInterface, which must be either Event
or an interface that inherits from
it, and optionally given a Realm realm, run these steps:
-
If realm is not given, then set it to null.
-
Let dictionary be the result of converting the JavaScript value undefined to the dictionary type accepted by eventInterface’s constructor. (This dictionary type will either be
EventInit
or a dictionary that inherits from it.)This does not work if members are required; see whatwg/dom#600.
-
Let event be the result of running the inner event creation steps with eventInterface, realm, the time of the occurrence that the event is signaling, and dictionary.
In macOS the time of the occurrence for input actions is available via the
timestamp
property ofNSEvent
objects. -
Initialize event’s
isTrusted
attribute to true. -
Return event.
Create an event is meant to be used by other specifications which need to separately create and dispatch events, instead of simply firing them. It ensures the event’s attributes are initialized to the correct defaults.
The inner event creation steps, given an interface, realm, time, and dictionary, are as follows:
-
Let event be the result of creating a new object using eventInterface. If realm is non-null, then use that Realm; otherwise, use the default behavior defined in Web IDL.
As of the time of this writing Web IDL does not yet define any default behavior; see heycam/webidl#135.
-
Set event’s initialized flag.
-
Initialize event’s
timeStamp
attribute to aDOMHighResTimeStamp
representing the high resolution time from the time origin to time.User agents should set a minimum resolution of event’s
timeStamp
attribute to 5 microseconds following the existing clock resolution recommendation. [HR-TIME] -
For each member → value in dictionary, if event has an attribute whose identifier is member, then initialize that attribute to value.
-
Run the event constructing steps with event.
-
Return event.
2.6. Defining event interfaces
In general, when defining a new interface that inherits from Event
please always ask
feedback from the WHATWG or the W3C WebApps WG community.
The CustomEvent
interface can be used as starting point.
However, do not introduce any init*Event()
methods as they are redundant with constructors. Interfaces that inherit
from the Event
interface that have such a method only have it
for historical reasons.
2.7. Interface EventTarget
In all current engines.
Opera7+Edge79+
Edge (Legacy)12+IE6+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
Node.js14.5.0+
In all current engines.
Opera7+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
In all current engines.
Opera7+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
[Exposed =(Window ,Worker ,AudioWorklet )]interface {
EventTarget constructor ();undefined addEventListener (DOMString ,
type EventListener ?,
callback optional (AddEventListenerOptions or boolean )= {});
options undefined removeEventListener (DOMString ,
type EventListener ?,
callback optional (EventListenerOptions or boolean )= {});
options boolean dispatchEvent (Event ); };
event callback interface {
EventListener undefined (
handleEvent Event ); };
event dictionary {
EventListenerOptions boolean =
capture false ; };dictionary :
AddEventListenerOptions EventListenerOptions {boolean =
passive false ;boolean =
once false ;AbortSignal ; };
signal
An EventTarget
object represents a target to which an event can be dispatched when something has occurred.
Each EventTarget
object has an associated event listener list (a list of zero or more event listeners). It is initially the empty list.
An event listener can be used to observe a specific event and consists of:
- type (a string)
- callback (null or an
EventListener
object) - capture (a boolean, initially false)
- passive (a boolean, initially false)
- once (a boolean, initially false)
- signal (null or an
AbortSignal
object) - removed (a boolean for bookkeeping purposes, initially false)
Although callback is an EventListener
object, an event listener is a broader concept as can be seen above.
Each EventTarget
object also has an associated get the parent algorithm,
which takes an event event, and returns an EventTarget
object. Unless
specified otherwise it returns null.
Nodes, shadow roots, and documents override the get the parent algorithm.
Each EventTarget
object can have an associated activation behavior algorithm. The activation behavior algorithm is passed an event, as indicated in the dispatch algorithm.
This exists because user agents perform certain actions for certain EventTarget
objects, e.g., the area
element, in response to synthetic MouseEvent
events whose type
attribute is click
. Web compatibility prevented it
from being removed and it is now the enshrined way of defining an activation of something. [HTML]
Each EventTarget
object that has activation behavior, can additionally
have both (not either) a legacy-pre-activation behavior algorithm
and a legacy-canceled-activation behavior algorithm.
These algorithms only exist for checkbox and radio input
elements and
are not to be used for anything else. [HTML]
target = new EventTarget();
-
Creates a new
EventTarget
object, which can be used by developers to dispatch and listen for events. target . addEventListener(type, callback [, options])
-
Appends an event listener for events whose
type
attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options’s
capture
.When set to true, options’s
capture
prevents callback from being invoked when the event’seventPhase
attribute value isBUBBLING_PHASE
. When false (or not present), callback will not be invoked when event’seventPhase
attribute value isCAPTURING_PHASE
. Either way, callback will be invoked if event’seventPhase
attribute value isAT_TARGET
.When set to true, options’s
passive
indicates that the callback will not cancel the event by invokingpreventDefault()
. This is used to enable performance optimizations described in § 2.8 Observing event listeners.When set to true, options’s
once
indicates that the callback will only be invoked once after which the event listener will be removed.If an
AbortSignal
is passed for options’ssignal
, then the event listener will be removed when signal is aborted.The event listener is appended to target’s event listener list and is not appended if it has the same type, callback, and capture.
target . removeEventListener(type, callback [, options])
-
Removes the event listener in target’s event listener list with the same type, callback, and options.
target . dispatchEvent(event)
-
Dispatches a synthetic event event to target and returns true if either event’s
cancelable
attribute value is false or itspreventDefault()
method was not invoked, and false otherwise.
To flatten options, run these steps:
-
If options is a boolean, then return options.
-
Return options["
capture
"].
To flatten more options, run these steps:
-
Let capture be the result of flattening options.
-
Let once and passive be false.
-
Let signal be null.
-
If options is a dictionary, then:
-
Return capture, passive, once, and signal.
In all current engines.
Opera51+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android59+iOS Safari14+Chrome for Android64+Android WebView64+Samsung Internet9.0+Opera Mobile47+
Node.js15.0.0+
The EventTarget()
constructor, when invoked,
must return a new EventTarget
.
Because of the defaults stated elsewhere, the returned EventTarget
's get the parent algorithm will return null, and it will have no activation behavior, legacy-pre-activation behavior, or legacy-canceled-activation behavior.
In the future we could allow custom get the parent algorithms. Let us know
if this would be useful for your programs. For now, all author-created EventTarget
s do not
participate in a tree structure.
To add an event listener, given an EventTarget
object eventTarget and an event listener listener, run these steps:
-
If eventTarget is a
ServiceWorkerGlobalScope
object, its service worker’s script resource’s has ever been evaluated flag is set, and listener’s type matches thetype
attribute value of any of the service worker events, then report a warning to the console that this might not give the expected results. [SERVICE-WORKERS] -
If signal is not null and its aborted flag is set, then return.
-
If listener’s callback is null, then return.
-
If eventTarget’s event listener list does not contain an event listener whose type is listener’s type, callback is listener’s callback, and capture is listener’s capture, then append listener to eventTarget’s event listener list.
-
If listener’s signal is not null, then add the following abort steps to it:
- Remove an event listener with eventTarget and listener.
The add an event listener concept exists to ensure event handlers use the same code path. [HTML]
In all current engines.
Opera7+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
Node.js14.5.0+
The addEventListener(type, callback, options)
method, when invoked, must run these steps:
-
Let capture, passive, and once be the result of flattening more options.
-
Add an event listener with this and an event listener whose type is type, callback is callback, capture is capture, passive is passive, once is once, and signal is signal.
To remove an event listener, given an EventTarget
object eventTarget and an event listener listener, run these steps:
-
If eventTarget is a
ServiceWorkerGlobalScope
object and its service worker’s set of event types to handle contains type, then report a warning to the console that this might not give the expected results. [SERVICE-WORKERS] -
Set listener’s removed to true and remove listener from eventTarget’s event listener list.
HTML needs this to define event handlers. [HTML]
To remove all event listeners, given an EventTarget
object eventTarget, for each listener of eventTarget’s event listener list, remove an event listener with eventTarget and listener.
HTML needs this to define document.open()
. [HTML]
EventTarget/removeEventListener
In all current engines.
Opera7+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
Node.js14.5.0+
The removeEventListener(type, callback, options)
method, when invoked, must run these steps:
-
Let capture be the result of flattening options.
-
If this’s event listener list contains an event listener whose type is type, callback is callback, and capture is capture, then remove an event listener with this and that event listener.
The event listener list will not contain multiple event listeners with equal type, callback, and capture, as add an event listener prevents that.
In all current engines.
Opera9+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari3+Chrome for Android18+Android WebView4+Samsung Internet1.0+Opera Mobile10.1+
Node.js14.5.0+
The dispatchEvent(event)
method, when
invoked, must run these steps:
-
If event’s dispatch flag is set, or if its initialized flag is not set, then throw an "
InvalidStateError
"DOMException
. -
Initialize event’s
isTrusted
attribute to false. -
Return the result of dispatching event to this.
2.8. Observing event listeners
In general, developers do not expect the presence of an event listener to be observable. The impact of an event listener is determined by its callback. That is, a developer adding a no-op event listener would not expect it to have any side effects.
Unfortunately, some event APIs have been designed such that implementing them efficiently
requires observing event listeners. This can make the presence of listeners observable in
that even empty listeners can have a dramatic performance impact on the behavior of the application.
For example, touch and wheel events which can be used to block asynchronous scrolling. In some cases
this problem can be mitigated by specifying the event to be cancelable
only when there is
at least one non-passive
listener. For example,
non-passive
TouchEvent
listeners must block scrolling, but if all
listeners are passive
then scrolling can be allowed to start in parallel by making the TouchEvent
uncancelable (so that calls to preventDefault()
are ignored). So code dispatching an event is able to observe the absence
of non-passive
listeners, and use that to clear the cancelable
property of the event being dispatched.
Ideally, any new event APIs are defined such that they do not need this property (use public-script-coord@w3.org for discussion).
2.9. Dispatching events
To dispatch an event to a target, with an optional legacy target override flag and an optional legacyOutputDidListenersThrowFlag, run these steps:
-
Set event’s dispatch flag.
-
Let targetOverride be target, if legacy target override flag is not given, and target’s associated
Document
otherwise. [HTML]legacy target override flag is only used by HTML and only when target is a
Window
object. -
Let activationTarget be null.
-
Let relatedTarget be the result of retargeting event’s relatedTarget against target.
-
If target is not relatedTarget or target is event’s relatedTarget, then:
-
Let touchTargets be a new list.
-
For each touchTarget of event’s touch target list, append the result of retargeting touchTarget against target to touchTargets.
-
Append to an event path with event, target, targetOverride, relatedTarget, touchTargets, and false.
-
Let isActivationEvent be true, if event is a
MouseEvent
object and event’stype
attribute is "click
", and false otherwise. -
If isActivationEvent is true and target has activation behavior, then set activationTarget to target.
-
Let slottable be target, if target is a slottable and is assigned, and null otherwise.
-
Let slot-in-closed-tree be false.
-
Let parent be the result of invoking target’s get the parent with event.
-
While parent is non-null:
-
If slottable is non-null:
-
Assert: parent is a slot.
-
Set slottable to null.
-
If parent’s root is a shadow root whose mode is "
closed
", then set slot-in-closed-tree to true.
-
-
If parent is a slottable and is assigned, then set slottable to parent.
-
Let relatedTarget be the result of retargeting event’s relatedTarget against parent.
-
Let touchTargets be a new list.
-
For each touchTarget of event’s touch target list, append the result of retargeting touchTarget against parent to touchTargets.
-
If parent is a
Window
object, or parent is a node and target’s root is a shadow-including inclusive ancestor of parent, then:-
If isActivationEvent is true, event’s
bubbles
attribute is true, activationTarget is null, and parent has activation behavior, then set activationTarget to parent. -
Append to an event path with event, parent, null, relatedTarget, touchTargets, and slot-in-closed-tree.
-
-
Otherwise, if parent is relatedTarget, then set parent to null.
-
Otherwise, set target to parent and then:
-
If isActivationEvent is true, activationTarget is null, and target has activation behavior, then set activationTarget to target.
-
Append to an event path with event, parent, target, relatedTarget, touchTargets, and slot-in-closed-tree.
-
-
If parent is non-null, then set parent to the result of invoking parent’s get the parent with event.
-
Set slot-in-closed-tree to false.
-
-
Let clearTargetsStruct be the last struct in event’s path whose shadow-adjusted target is non-null.
-
Let clearTargets be true if clearTargetsStruct’s shadow-adjusted target, clearTargetsStruct’s relatedTarget, or an
EventTarget
object in clearTargetsStruct’s touch target list is a node and its root is a shadow root, and false otherwise. -
If activationTarget is non-null and activationTarget has legacy-pre-activation behavior, then run activationTarget’s legacy-pre-activation behavior.
-
For each struct in event’s path, in reverse order:
-
If struct’s shadow-adjusted target is non-null, then set event’s
eventPhase
attribute toAT_TARGET
. -
Otherwise, set event’s
eventPhase
attribute toCAPTURING_PHASE
. -
Invoke with struct, event, "
capturing
", and legacyOutputDidListenersThrowFlag if given.
-
-
For each struct in event’s path:
-
If struct’s shadow-adjusted target is non-null, then set event’s
eventPhase
attribute toAT_TARGET
. -
Otherwise:
-
Set event’s
eventPhase
attribute toBUBBLING_PHASE
.
-
Invoke with struct, event, "
bubbling
", and legacyOutputDidListenersThrowFlag if given.
-
-
-
Set event’s
eventPhase
attribute toNONE
. -
Set event’s
currentTarget
attribute to null. -
Set event’s path to the empty list.
-
Unset event’s dispatch flag, stop propagation flag, and stop immediate propagation flag.
-
If clearTargets, then:
-
Set event’s target to null.
-
Set event’s relatedTarget to null.
-
Set event’s touch target list to the empty list.
-
-
If activationTarget is non-null, then:
-
If event’s canceled flag is unset, then run activationTarget’s activation behavior with event.
-
Otherwise, if activationTarget has legacy-canceled-activation behavior, then run activationTarget’s legacy-canceled-activation behavior.
-
-
Return false if event’s canceled flag is set, and true otherwise.
To append to an event path, given an event, invocationTarget, shadowAdjustedTarget, relatedTarget, touchTargets, and a slot-in-closed-tree, run these steps:
-
Let invocationTargetInShadowTree be false.
-
If invocationTarget is a node and its root is a shadow root, then set invocationTargetInShadowTree to true.
-
Let root-of-closed-tree be false.
-
If invocationTarget is a shadow root whose mode is "
closed
", then set root-of-closed-tree to true. -
Append a new struct to event’s path whose invocation target is invocationTarget, invocation-target-in-shadow-tree is invocationTargetInShadowTree, shadow-adjusted target is shadowAdjustedTarget, relatedTarget is relatedTarget, touch target list is touchTargets, root-of-closed-tree is root-of-closed-tree, and slot-in-closed-tree is slot-in-closed-tree.
To invoke, given a struct, event, phase, and an optional legacyOutputDidListenersThrowFlag, run these steps:
-
Set event’s target to the shadow-adjusted target of the last struct in event’s path, that is either struct or preceding struct, whose shadow-adjusted target is non-null.
-
Set event’s relatedTarget to struct’s relatedTarget.
-
Set event’s touch target list to struct’s touch target list.
-
If event’s stop propagation flag is set, then return.
-
Initialize event’s
currentTarget
attribute to struct’s invocation target. -
Let listeners be a clone of event’s
currentTarget
attribute value’s event listener list.This avoids event listeners added after this point from being run. Note that removal still has an effect due to the removed field.
-
Let invocationTargetInShadowTree be struct’s invocation-target-in-shadow-tree.
-
Let found be the result of running inner invoke with event, listeners, phase, invocationTargetInShadowTree, and legacyOutputDidListenersThrowFlag if given.
-
If found is false and event’s
isTrusted
attribute is true, then:-
Let originalEventType be event’s
type
attribute value. -
If event’s
type
attribute value is a match for any of the strings in the first column in the following table, set event’stype
attribute value to the string in the second column on the same row as the matching string, and return otherwise.Event type Legacy event type " animationend
"" webkitAnimationEnd
"" animationiteration
"" webkitAnimationIteration
"" animationstart
"" webkitAnimationStart
"" transitionend
"" webkitTransitionEnd
" -
Inner invoke with event, listeners, phase, invocationTargetInShadowTree, and legacyOutputDidListenersThrowFlag if given.
-
Set event’s
type
attribute value to originalEventType.
-
To inner invoke, given an event, listeners, phase, invocationTargetInShadowTree, and an optional legacyOutputDidListenersThrowFlag, run these steps:
-
Let found be false.
-
For each listener in listeners, whose removed is false:
-
If event’s
type
attribute value is not listener’s type, then continue. -
Set found to true.
-
If phase is "
capturing
" and listener’s capture is false, then continue. -
If phase is "
bubbling
" and listener’s capture is true, then continue. -
If listener’s once is true, then remove listener from event’s
currentTarget
attribute value’s event listener list. -
Let global be listener callback’s associated Realm’s global object.
-
Let currentEvent be undefined.
-
If global is a
Window
object, then:-
Set currentEvent to global’s current event.
-
If invocationTargetInShadowTree is false, then set global’s current event to event.
-
-
If listener’s passive is true, then set event’s in passive listener flag.
-
Call a user object’s operation with listener’s callback, "
handleEvent
", « event », and event’scurrentTarget
attribute value. If this throws an exception, then:-
Set legacyOutputDidListenersThrowFlag if given.
The legacyOutputDidListenersThrowFlag is only used by Indexed Database API. [INDEXEDDB]
-
Unset event’s in passive listener flag.
-
If global is a
Window
object, then set global’s current event to currentEvent. -
If event’s stop immediate propagation flag is set, then return found.
-
-
Return found.
2.10. Firing events
To fire an event named e at target, optionally using an eventConstructor, with a description of how IDL attributes are to be initialized, and a legacy target override flag, run these steps:
-
If eventConstructor is not given, then let eventConstructor be
Event
. -
Let event be the result of creating an event given eventConstructor, in the relevant Realm of target.
-
Initialize event’s
type
attribute to e. -
Initialize any other IDL attributes of event as described in the invocation of this algorithm.
This also allows for the
isTrusted
attribute to be set to false. -
Return the result of dispatching event at target, with legacy target override flag set if set.
Fire in the context of DOM is short for creating, initializing, and dispatching an event. Fire an event makes that process easier to write down.
If the event needs its bubbles
or cancelable
attribute initialized,
one could write "fire an event named submit
at target with its cancelable
attribute initialized to true".
Or, when a custom constructor is needed, "fire an event named click
at target using MouseEvent
with its detail
attribute initialized to 1".
Occasionally the return value is important:
-
Let doAction be the result of firing an event named
like
at target. -
If doAction is true, then …
2.11. Action versus occurrence
An event signifies an occurrence, not an action. Phrased differently, it
represents a notification from an algorithm and can be used to influence the future course
of that algorithm (e.g., through invoking preventDefault()
). Events must not be
used as actions or initiators that cause some algorithm to start running. That is not what
they are for.
This is called out here specifically because previous iterations of the DOM had a concept of "default actions" associated with events that gave folks all the wrong ideas. Events do not represent or cause actions, they can only be used to influence an ongoing one.
3. Aborting ongoing activities
Though promises do not have a built-in aborting mechanism, many APIs using them require abort
semantics. AbortController
is meant to support these requirements by providing an abort()
method that toggles the state of a corresponding AbortSignal
object.
The API which wishes to support aborting can accept an AbortSignal
object, and use its state to
determine how to proceed.
APIs that rely upon AbortController
are encouraged to respond to abort()
by rejecting any unsettled promise with a new "AbortError
" DOMException
.
A hypothetical doAmazingness({ ... })
method could accept an AbortSignal
object
in order to support aborting as follows:
const controller = new AbortController();
const signal = controller. signal;
startSpinner();
doAmazingness({ ..., signal })
. then( result => ...)
. catch ( err => {
if ( err. name == 'AbortError' ) return ;
showUserErrorMessage();
})
. then(() => stopSpinner());
// …
controller. abort();
doAmazingness
could be implemented as follows:
function doAmazingness({ signal}) {
if ( signal. aborted) {
return Promise. reject( new DOMException( 'Aborted' , 'AbortError' ));
}
return new Promise(( resolve, reject) => {
// Begin doing amazingness, and call resolve(result) when done.
// But also, watch for signals:
signal. addEventListener( 'abort' , () => {
// Stop doing amazingness, and:
reject( new DOMException( 'Aborted' , 'AbortError' ));
});
});
}
APIs that require more granular control could extend both AbortController
and AbortSignal
objects according to their needs.
3.1. Interface AbortController
In all current engines.
Opera53+Edge79+
Edge (Legacy)16+IENone
Firefox for Android57+iOS Safari12.2+Chrome for Android66+Android WebView66+Samsung Internet9.0+Opera Mobile47+
Node.js15.0.0+
[Exposed =(Window ,Worker )]interface {
AbortController constructor (); [SameObject ]readonly attribute AbortSignal signal ;undefined abort (); };
controller = new AbortController()
- Returns a new controller whose
signal
is set to a newly createdAbortSignal
object. controller . signal
- Returns the
AbortSignal
object associated with this object. controller . abort()
- Invoking this method will set this object’s
AbortSignal
's aborted flag and signal to any observers that the associated activity is to be aborted.
An AbortController
object has an associated signal (an AbortSignal
object).
AbortController/AbortController
In all current engines.
Opera53+Edge79+
Edge (Legacy)16+IENone
Firefox for Android57+iOS Safari12.2+Chrome for Android66+Android WebView66+Samsung Internet9.0+Opera Mobile47+
Node.js15.0.0+
The new AbortController()
constructor steps are:
-
Let signal be a new
AbortSignal
object.
In all current engines.
Opera53+Edge79+
Edge (Legacy)16+IENone
Firefox for Android57+iOS Safari12.2+Chrome for Android66+Android WebView66+Samsung Internet9.0+Opera Mobile47+
Node.js15.0.0+
The signal
getter steps are to return this’s signal.
In all current engines.
Opera53+Edge79+
Edge (Legacy)16+IENone
Firefox for Android57+iOS Safari12.2+Chrome for Android66+Android WebView66+Samsung Internet9.0+Opera Mobile47+
Node.js15.0.0+
The abort()
method steps are to signal abort on this’s signal.
3.2. Interface AbortSignal
In all current engines.
Opera53+Edge79+
Edge (Legacy)16+IENone
Firefox for Android57+iOS Safari11.3+Chrome for Android66+Android WebView66+Samsung Internet9.0+Opera Mobile47+
Node.js15.0.0+
[Exposed =(Window ,Worker )]interface :
AbortSignal EventTarget {readonly attribute boolean aborted ;attribute EventHandler onabort ; };
signal . aborted
- Returns true if this
AbortSignal
'sAbortController
has signaled to abort, and false otherwise.
An AbortSignal
object has an associated aborted flag. It is
unset unless specified otherwise.
An AbortSignal
object has associated abort algorithms, which is a set of algorithms which are to be executed when its aborted flag is
set. Unless specified otherwise, its value is the empty set.
To add an algorithm algorithm to an AbortSignal
object signal, run these steps:
-
If signal’s aborted flag is set, then return.
-
Append algorithm to signal’s abort algorithms.
To remove an algorithm algorithm from an AbortSignal
signal, remove algorithm from signal’s abort algorithms.
The abort algorithms enable APIs with complex
requirements to react in a reasonable way to abort()
. For example, a given API’s aborted flag might need to be propagated to a cross-thread environment, such as a
service worker.
In all current engines.
Opera53+Edge79+
Edge (Legacy)16+IENone
Firefox for Android57+iOS Safari11.3+Chrome for Android66+Android WebView66+Samsung Internet9.0+Opera Mobile47+
Node.js15.0.0+
The aborted
getter steps are to return true if this’s aborted flag is set; otherwise false.
In all current engines.
Opera53+Edge79+
Edge (Legacy)16+IENone
Firefox for Android57+iOS Safari11.3+Chrome for Android66+Android WebView66+Samsung Internet9.0+Opera Mobile47+
Node.js15.0.0+
In all current engines.
Opera53+Edge79+
Edge (Legacy)16+IENone
Firefox for Android57+iOS Safari11.3+Chrome for Android66+Android WebView66+Samsung Internet9.0+Opera Mobile47+
Node.js15.0.0+
The onabort
attribute is an event handler IDL attribute for the onabort
event handler, whose event handler event type is abort
.
Changes to an AbortSignal
object represent the wishes of the corresponding AbortController
object, but an API observing the AbortSignal
object can chose to ignore
them. For instance, if the operation has already completed.
To signal abort, given a AbortSignal
object signal, run these steps:
-
If signal’s aborted flag is set, then return.
-
Set signal’s aborted flag.
-
For each algorithm in signal’s abort algorithms: run algorithm.
-
Empty signal’s abort algorithms.
-
Fire an event named
abort
at signal.
A followingSignal (an AbortSignal
) is made to follow a parentSignal (an AbortSignal
) by running
these steps:
-
If followingSignal’s aborted flag is set, then return.
-
If parentSignal’s aborted flag is set, then signal abort on followingSignal.
-
Otherwise, add the following abort steps to parentSignal:
-
Signal abort on followingSignal.
-
3.3. Using AbortController
and AbortSignal
objects in
APIs
Any web platform API using promises to represent operations that can be aborted must adhere to the following:
- Accept
AbortSignal
objects through asignal
dictionary member. - Convey that the operation got aborted by rejecting the promise with an
"
AbortError
"DOMException
. - Reject immediately if the
AbortSignal
's aborted flag is already set, otherwise: - Use the abort algorithms mechanism to observe changes to the
AbortSignal
object and do so in a manner that does not lead to clashes with other observers.
The steps for a promise-returning method doAmazingness(options)
could be as
follows:
-
Let p be a new promise.
-
If options’
signal
member is present, then:-
If options’
signal
’s aborted flag is set, then reject p with an "AbortError
"DOMException
and return p. -
Add the following abort steps to options’
signal
:-
Stop doing amazing things.
-
Reject p with an "
AbortError
"DOMException
.
-
-
-
Run these steps in parallel:
-
Let amazingResult be the result of doing some amazing things.
-
Resolve p with amazingResult.
-
-
Return p.
APIs not using promises should still adhere to the above as much as possible.
4. Nodes
4.1. Introduction to "The DOM"
In its original sense, "The DOM" is an API for accessing and manipulating documents (in particular, HTML and XML documents). In this specification, the term "document" is used for any markup-based resource, ranging from short static documents to long essays or reports with rich multimedia, as well as to fully-fledged interactive applications.
Each such document is represented as a node tree. Some of the nodes in a tree can have children, while others are always leaves.
To illustrate, consider this HTML document:
<!DOCTYPE html> < html class = e > < head >< title > Aliens?</ title ></ head > < body > Why yes.</ body > </ html >
It is represented as follows:
Note that, due to the magic that is HTML parsing, not all ASCII whitespace were turned into Text
nodes, but the general concept is
clear. Markup goes in, a tree of nodes comes out.
The most excellent Live DOM Viewer can be used to explore this matter in more detail.
4.2. Node tree
Document
, DocumentType
, DocumentFragment
, Element
, Text
, ProcessingInstruction
, and Comment
objects (simply called nodes) participate in a tree, simply named the node tree.
A node tree is constrained as follows, expressed as a relationship between the type of node and its allowed children:
Document
-
In tree order:
-
Zero or more nodes each of which is
ProcessingInstruction
orComment
. -
Optionally one
DocumentType
node. -
Zero or more nodes each of which is
ProcessingInstruction
orComment
. -
Optionally one
Element
node. -
Zero or more nodes each of which is
ProcessingInstruction
orComment
.
-
DocumentFragment
Element
-
Zero or more nodes each of which is
Element
,Text
,ProcessingInstruction
, orComment
. DocumentType
Text
ProcessingInstruction
Comment
-
None.
To determine the length of a node node, switch on node:
DocumentType
-
Zero.
Text
ProcessingInstruction
Comment
- Any other node
-
Its number of children.
A node is considered empty if its length is zero.
4.2.1. Document tree
A document tree is a node tree whose root is a document.
The document element of a document is the element whose parent is that document, if it exists, and null otherwise.
Per the node tree constraints, there can be only one such element.
An element is in a document tree if its root is a document.
An element is in a document if it is in a document tree. The term in a document is no longer supposed to be used. It indicates that the standard using it has not been updated to account for shadow trees.
4.2.2. Shadow tree
A shadow tree is a node tree whose root is a shadow root.
A shadow root is always attached to another node tree through its host. A shadow tree is therefore never alone. The node tree of a shadow root’s host is sometimes referred to as the light tree.
A shadow tree’s corresponding light tree can be a shadow tree itself.
An element is connected if its shadow-including root is a document.
4.2.2.1. Slots
In all current engines.
Opera40+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android63+iOS Safari10+Chrome for Android53+Android WebView53+Samsung Internet6.0+Opera Mobile41+
A shadow tree contains zero or more elements that are slots.
A slot can only be created through HTML’s slot
element.
A slot has an associated name (a string). Unless stated otherwise it is the empty string.
Use these attribute change steps to update a slot’s name:
-
If element is a slot, localName is
name
, and namespace is null, then:-
If value is oldValue, then return.
-
If value is null and oldValue is the empty string, then return.
-
If value is the empty string and oldValue is null, then return.
-
If value is null or the empty string, then set element’s name to the empty string.
-
Otherwise, set element’s name to value.
-
Run assign slottables for a tree with element’s root.
-
The first slot in a shadow tree, in tree order, whose name is the empty string, is sometimes known as the "default slot".
A slot has an associated assigned nodes (a list of slottables). Unless stated otherwise it is empty.
4.2.2.2. Slottables
Element
and Text
nodes are slottables.
A slottable has an associated name (a string). Unless stated otherwise it is the empty string.
Use these attribute change steps to update a slottable’s name:
-
If localName is
slot
and namespace is null, then:-
If value is oldValue, then return.
-
If value is null and oldValue is the empty string, then return.
-
If value is the empty string and oldValue is null, then return.
-
If value is null or the empty string, then set element’s name to the empty string.
-
Otherwise, set element’s name to value.
-
If element is assigned, then run assign slottables for element’s assigned slot.
-
Run assign a slot for element.
-
A slottable has an associated assigned slot (null or a slot). Unless stated otherwise it is null. A slottable is assigned if its assigned slot is non-null.
4.2.2.3. Finding slots and slottables
To find a slot for a given slottable slottable and an optional open flag (unset unless stated otherwise), run these steps:
-
If slottable’s parent is null, then return null.
-
Let shadow be slottable’s parent’s shadow root.
-
If shadow is null, then return null.
-
If the open flag is set and shadow’s mode is not "
open
", then return null. -
Return the first slot in tree order in shadow’s descendants whose name is slottable’s name, if any, and null otherwise.
To find slottables for a given slot slot, run these steps:
-
Let result be an empty list.
-
If slot’s root is not a shadow root, then return result.
-
For each slottable child of host, slottable, in tree order:
-
Let foundSlot be the result of finding a slot given slottable.
-
If foundSlot is slot, then append slottable to result.
-
-
Return result.
To find flattened slottables for a given slot slot, run these steps:
-
Let result be an empty list.
-
If slot’s root is not a shadow root, then return result.
-
Let slottables be the result of finding slottables given slot.
-
If slottables is the empty list, then append each slottable child of slot, in tree order, to slottables.
-
For each node in slottables:
-
If node is a slot whose root is a shadow root, then:
-
Let temporaryResult be the result of finding flattened slottables given node.
-
Append each slottable in temporaryResult, in order, to result.
-
-
Otherwise, append node to result.
-
-
Return result.
4.2.2.4. Assigning slottables and slots
To assign slottables for a slot slot, run these steps:
-
Let slottables be the result of finding slottables for slot.
-
If slottables and slot’s assigned nodes are not identical, then run signal a slot change for slot.
-
Set slot’s assigned nodes to slottables.
-
For each slottable in slottables, set slottable’s assigned slot to slot.
To assign slottables for a tree, given a node root, run assign slottables for each slot slot in root’s inclusive descendants, in tree order.
To assign a slot, given a slottable slottable, run these steps:
-
Let slot be the result of finding a slot with slottable.
-
If slot is non-null, then run assign slottables for slot.
4.2.2.5. Signaling slot change
Each similar-origin window agent has signal slots (a set of slots), which is initially empty. [HTML]
To signal a slot change, for a slot slot, run these steps:
-
Append slot to slot’s relevant agent’s signal slots.
4.2.3. Mutation algorithms
To ensure pre-insertion validity of a node into a parent before a child, run these steps:
-
If parent is not a
Document
,DocumentFragment
, orElement
node, then throw a "HierarchyRequestError
"DOMException
. -
If node is a host-including inclusive ancestor of parent, then throw a "
HierarchyRequestError
"DOMException
. -
If child is non-null and its parent is not parent, then throw a "
NotFoundError
"DOMException
. -
If node is not a
DocumentFragment
,DocumentType
,Element
,Text
,ProcessingInstruction
, orComment
node, then throw a "HierarchyRequestError
"DOMException
. -
If either node is a
Text
node and parent is a document, or node is a doctype and parent is not a document, then throw a "HierarchyRequestError
"DOMException
. -
If parent is a document, and any of the statements below, switched on node, are true, then throw a "
HierarchyRequestError
"DOMException
.DocumentFragment
node-
If node has more than one element child or has a
Text
node child.Otherwise, if node has one element child and either parent has an element child, child is a doctype, or child is non-null and a doctype is following child.
- element
-
parent has an element child, child is a doctype, or child is non-null and a doctype is following child.
- doctype
-
parent has a doctype child, child is non-null and an element is preceding child, or child is null and parent has an element child.
To pre-insert a node into a parent before a child, run these steps:
-
Ensure pre-insertion validity of node into parent before child.
-
Let referenceChild be child.
-
If referenceChild is node, then set referenceChild to node’s next sibling.
-
Insert node into parent before referenceChild.
-
Return node.
Specifications may define insertion steps for all or some nodes. The algorithm is passed insertedNode, as indicated in the insert algorithm below.
Specifications may define children changed steps for all or some nodes. The algorithm is passed no argument and is called from insert, remove, and replace data.
To insert a node into a parent before a child, with an optional suppress observers flag, run these steps:
-
Let nodes be node’s children, if node is a
DocumentFragment
node; otherwise « node ». -
Let count be nodes’s size.
-
If count is 0, then return.
-
If node is a
DocumentFragment
node, then:-
Queue a tree mutation record for node with « », nodes, null, and null.
This step intentionally does not pay attention to the suppress observers flag.
-
If child is non-null, then:
-
For each live range whose start node is parent and start offset is greater than child’s index, increase its start offset by count.
-
For each live range whose end node is parent and end offset is greater than child’s index, increase its end offset by count.
-
-
Let previousSibling be child’s previous sibling or parent’s last child if child is null.
-
For each node in nodes, in tree order:
-
Adopt node into parent’s node document.
-
Otherwise, insert node into parent’s children before child’s index.
-
If parent is a shadow host and node is a slottable, then assign a slot for node.
-
If parent’s root is a shadow root, and parent is a slot whose assigned nodes is the empty list, then run signal a slot change for parent.
-
Run assign slottables for a tree with node’s root.
-
For each shadow-including inclusive descendant inclusiveDescendant of node, in shadow-including tree order:
-
Run the insertion steps with inclusiveDescendant.
-
If inclusiveDescendant is connected, then:
-
If inclusiveDescendant is custom, then enqueue a custom element callback reaction with inclusiveDescendant, callback name "
connectedCallback
", and an empty argument list. -
Otherwise, try to upgrade inclusiveDescendant.
If this successfully upgrades inclusiveDescendant, its
connectedCallback
will be enqueued automatically during the upgrade an element algorithm.
-
-
-
-
If suppress observers flag is unset, then queue a tree mutation record for parent with nodes, « », previousSibling, and child.
-
Run the children changed steps for parent.
To append a node to a parent, pre-insert node into parent before null.
To replace a child with node within a parent, run these steps:
-
If parent is not a
Document
,DocumentFragment
, orElement
node, then throw a "HierarchyRequestError
"DOMException
. -
If node is a host-including inclusive ancestor of parent, then throw a "
HierarchyRequestError
"DOMException
. -
If child’s parent is not parent, then throw a "
NotFoundError
"DOMException
. -
If node is not a
DocumentFragment
,DocumentType
,Element
,Text
,ProcessingInstruction
, orComment
node, then throw a "HierarchyRequestError
"DOMException
. -
If either node is a
Text
node and parent is a document, or node is a doctype and parent is not a document, then throw a "HierarchyRequestError
"DOMException
. -
If parent is a document, and any of the statements below, switched on node, are true, then throw a "
HierarchyRequestError
"DOMException
.DocumentFragment
node-
If node has more than one element child or has a
Text
node child.Otherwise, if node has one element child and either parent has an element child that is not child or a doctype is following child.
- element
-
parent has an element child that is not child or a doctype is following child.
- doctype
-
parent has a doctype child that is not child, or an element is preceding child.
The above statements differ from the pre-insert algorithm.
-
Let referenceChild be child’s next sibling.
-
If referenceChild is node, then set referenceChild to node’s next sibling.
-
Let previousSibling be child’s previous sibling.
-
Let removedNodes be the empty set.
-
If child’s parent is non-null, then:
-
Set removedNodes to « child ».
-
Remove child with the suppress observers flag set.
The above can only be false if child is node.
-
-
Let nodes be node’s children if node is a
DocumentFragment
node; otherwise « node ». -
Insert node into parent before referenceChild with the suppress observers flag set.
-
Queue a tree mutation record for parent with nodes, removedNodes, previousSibling, and referenceChild.
-
Return child.
To replace all with a node within a parent, run these steps:
-
Let removedNodes be parent’s children.
-
Let addedNodes be the empty set.
-
If node is a
DocumentFragment
node, then set addedNodes to node’s children. -
Otherwise, if node is non-null, set addedNodes to « node ».
-
Remove all parent’s children, in tree order, with the suppress observers flag set.
-
If node is non-null, then insert node into parent before null with the suppress observers flag set.
-
If either addedNodes or removedNodes is not empty, then queue a tree mutation record for parent with addedNodes, removedNodes, null, and null.
This algorithm does not make any checks with regards to the node tree constraints. Specification authors need to use it wisely.
To pre-remove a child from a parent, run these steps:
-
If child’s parent is not parent, then throw a "
NotFoundError
"DOMException
. -
Remove child.
-
Return child.
Specifications may define removing steps for all or some nodes. The algorithm is passed removedNode, and optionally oldParent, as indicated in the remove algorithm below.
To remove a node, with an optional suppress observers flag, run these steps:
-
Let parent be node’s parent
-
Assert: parent is non-null.
-
Let index be node’s index.
-
For each live range whose start node is an inclusive descendant of node, set its start to (parent, index).
-
For each live range whose end node is an inclusive descendant of node, set its end to (parent, index).
-
For each live range whose start node is parent and start offset is greater than index, decrease its start offset by 1.
-
For each live range whose end node is parent and end offset is greater than index, decrease its end offset by 1.
-
For each
NodeIterator
object iterator whose root’s node document is node’s node document, run theNodeIterator
pre-removing steps given node and iterator. -
Let oldPreviousSibling be node’s previous sibling.
-
Let oldNextSibling be node’s next sibling.
-
If node is assigned, then run assign slottables for node’s assigned slot.
-
If parent’s root is a shadow root, and parent is a slot whose assigned nodes is the empty list, then run signal a slot change for parent.
-
If node has an inclusive descendant that is a slot, then:
-
Run assign slottables for a tree with parent’s root.
-
Run assign slottables for a tree with node.
-
-
Run the removing steps with node and parent.
-
Let isParentConnected be parent’s connected.
-
If node is custom and isParentConnected is true, then enqueue a custom element callback reaction with node, callback name "
disconnectedCallback
", and an empty argument list.It is intentional for now that custom elements do not get parent passed. This might change in the future if there is a need.
-
For each shadow-including descendant descendant of node, in shadow-including tree order, then:
-
Run the removing steps with descendant.
-
If descendant is custom and isParentConnected is true, then enqueue a custom element callback reaction with descendant, callback name "
disconnectedCallback
", and an empty argument list.
-
-
For each inclusive ancestor inclusiveAncestor of parent, and then for each registered of inclusiveAncestor’s registered observer list, if registered’s options’s
subtree
is true, then append a new transient registered observer whose observer is registered’s observer, options is registered’s options, and source is registered to node’s registered observer list. -
If suppress observers flag is unset, then queue a tree mutation record for parent with « », « node », oldPreviousSibling, and oldNextSibling.
-
Run the children changed steps for parent.
4.2.4. Mixin NonElementParentNode
Web compatibility prevents the getElementById()
method from being exposed on elements (and therefore on ParentNode
).
interface mixin {
NonElementParentNode Element ?getElementById (DOMString ); };
elementId Document includes NonElementParentNode ;DocumentFragment includes NonElementParentNode ;
node . getElementById(elementId)
-
Returns the first element within node’s descendants whose ID is elementId.
In all current engines.
Opera7+Edge79+
Edge (Legacy)12+IE5.5+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
The getElementById(elementId)
method, when invoked, must return the first element, in tree order, within this’s descendants, whose ID is elementId, and null if
there is no such element otherwise.
4.2.5. Mixin DocumentOrShadowRoot
In all current engines.
Opera40+Edge79+
Edge (Legacy)12+IEYes
Firefox for AndroidYesiOS SafariYesChrome for Android53+Android WebView53+Samsung Internet6.0+Opera Mobile41+
interface mixin { };
DocumentOrShadowRoot Document includes DocumentOrShadowRoot ;ShadowRoot includes DocumentOrShadowRoot ;
The DocumentOrShadowRoot
mixin is expected to be used by other
standards that want to define APIs shared between documents and shadow roots.
4.2.6. Mixin ParentNode
To convert nodes into a node, given nodes and document, run these steps:
-
Let node be null.
-
Replace each string in nodes with a new
Text
node whose data is the string and node document is document. -
Otherwise, set node to a new
DocumentFragment
whose node document is document, and then append each node in nodes, if any, to it. -
Return node.
In all current engines.
Opera10+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS SafariYesChrome for AndroidYesAndroid WebViewYesSamsung InternetYesOpera MobileYes
interface mixin { [
ParentNode SameObject ]readonly attribute HTMLCollection children ;readonly attribute Element ?firstElementChild ;readonly attribute Element ?lastElementChild ;readonly attribute unsigned long childElementCount ; [CEReactions ,Unscopable ]undefined prepend ((Node or DOMString )...); [
nodes CEReactions ,Unscopable ]undefined append ((Node or DOMString )...); [
nodes CEReactions ,Unscopable ]undefined replaceChildren ((Node or DOMString )...);
nodes Element ?querySelector (DOMString ); [
selectors NewObject ]NodeList querySelectorAll (DOMString ); };
selectors Document includes ParentNode ;DocumentFragment includes ParentNode ;Element includes ParentNode ;
collection = node .
children
- Returns the child elements.
element = node .
firstElementChild
- Returns the first child that is an element, and null otherwise.
element = node .
lastElementChild
- Returns the last child that is an element, and null otherwise.
node . prepend(nodes)
-
Inserts nodes before the first child of node, while replacing strings in nodes with equivalent
Text
nodes.Throws a "
HierarchyRequestError
"DOMException
if the constraints of the node tree are violated. node . append(nodes)
-
Inserts nodes after the last child of node, while replacing strings in nodes with equivalent
Text
nodes.Throws a "
HierarchyRequestError
"DOMException
if the constraints of the node tree are violated. node . replaceChildren(nodes)
-
Replace all children of node with nodes, while replacing strings in nodes with equivalent
Text
nodes.Throws a "
HierarchyRequestError
"DOMException
if the constraints of the node tree are violated. node . querySelector(selectors)
- Returns the first element that is a descendant of node that matches selectors.
node . querySelectorAll(selectors)
- Returns all element descendants of node that match selectors.
In all current engines.
Opera10+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari9+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
The children
attribute’s getter must return an HTMLCollection
collection rooted at this matching only element children.
In all current engines.
Opera10+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS SafariYesChrome for AndroidYesAndroid WebViewYesSamsung InternetYesOpera MobileYes
The firstElementChild
attribute’s getter must
return the first child that is an element, and null otherwise.
In all current engines.
Opera10+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS SafariYesChrome for AndroidYesAndroid WebViewYesSamsung InternetYesOpera MobileYes
The lastElementChild
attribute’s getter must
return the last child that is an element, and null otherwise.
In all current engines.
Opera10+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS SafariYesChrome for AndroidYesAndroid WebViewYesSamsung InternetYesOpera MobileYes
The childElementCount
attribute’s getter must
return the number of children of this that are elements.
In all current engines.
Opera39+Edge79+
Edge (Legacy)17+IENone
Firefox for Android49+iOS Safari10+Chrome for Android54+Android WebView54+Samsung Internet6.0+Opera Mobile41+
The prepend(nodes)
method, when invoked,
must run these steps:
-
Let node be the result of converting nodes into a node given nodes and this’s node document.
-
Pre-insert node into this before this’s first child.
In all current engines.
Opera39+Edge79+
Edge (Legacy)17+IENone
Firefox for Android49+iOS Safari10+Chrome for Android54+Android WebView54+Samsung Internet6.0+Opera Mobile41+
The append(nodes)
method, when invoked,
must run these steps:
-
Let node be the result of converting nodes into a node given nodes and this’s node document.
Opera72+Edge86+
Edge (Legacy)NoneIENone
Firefox for AndroidNoneiOS SafariNoneChrome for Android86+Android WebView86+Samsung InternetNoneOpera MobileNone
The replaceChildren(nodes)
method, when invoked,
must run these steps:
-
Let node be the result of converting nodes into a node given nodes and this’s node document.
-
Ensure pre-insertion validity of node into this before null.
-
Replace all with node within this.
In all current engines.
Opera10+Edge79+
Edge (Legacy)12+IE8+
Firefox for Android4+iOS Safari3+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
In all current engines.
Opera10+Edge79+
Edge (Legacy)12+IE9+
Firefox for AndroidYesiOS Safari3.2+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile10.1+
The querySelector(selectors)
method,
when invoked, must return the first result of running scope-match a selectors string selectors against this, if the result is not an empty list, and null otherwise.
In all current engines.
Opera10+Edge79+
Edge (Legacy)12+IE8+
Firefox for Android4+iOS Safari3+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
In all current engines.
Opera10+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari2+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
In all current engines.
Opera10+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari2+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
In all current engines.
Opera10+Edge79+
Edge (Legacy)12+IE9+
Firefox for AndroidYesiOS Safari3.2+Chrome for AndroidYesAndroid WebViewYesSamsung InternetYesOpera Mobile10.1+
The querySelectorAll(selectors)
method, when invoked, must return the static result of running scope-match a selectors string selectors against this.
4.2.7. Mixin NonDocumentTypeChildNode
In all current engines.
Opera10+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS SafariYesChrome for AndroidYesAndroid WebViewYesSamsung InternetYesOpera Mobile10.1+
Web compatibility prevents the previousElementSibling
and nextElementSibling
attributes from being exposed on doctypes (and therefore on ChildNode
).
interface mixin {
NonDocumentTypeChildNode readonly attribute Element ?previousElementSibling ;readonly attribute Element ?nextElementSibling ; };Element includes NonDocumentTypeChildNode ;CharacterData includes NonDocumentTypeChildNode ;
element = node .
previousElementSibling
- Returns the first preceding sibling that is an element, and null otherwise.
element = node .
nextElementSibling
- Returns the first following sibling that is an element, and null otherwise.
NonDocumentTypeChildNode/previousElementSibling
In all current engines.
Opera10+Edge79+
Edge (Legacy)12+IENone
Firefox for Android4+iOS SafariYesChrome for AndroidYesAndroid WebViewYesSamsung InternetYesOpera Mobile10.1+
The previousElementSibling
attribute’s getter must return the first preceding sibling that is an element, and null otherwise.
NonDocumentTypeChildNode/nextElementSibling
In all current engines.
Opera10+Edge79+
Edge (Legacy)12+IENone
Firefox for Android4+iOS SafariYesChrome for AndroidYesAndroid WebViewYesSamsung InternetYesOpera Mobile10.1+
The nextElementSibling
attribute’s
getter must return the first following sibling that is an element, and null otherwise.
4.2.8. Mixin ChildNode
In all current engines.
Opera10+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android23+iOS SafariYesChrome for AndroidYesAndroid WebViewYesSamsung InternetYesOpera Mobile10.1+
interface mixin { [
ChildNode CEReactions ,Unscopable ]undefined before ((Node or DOMString )...); [
nodes CEReactions ,Unscopable ]undefined after ((Node or DOMString )...); [
nodes CEReactions ,Unscopable ]undefined replaceWith ((Node or DOMString )...); [
nodes CEReactions ,Unscopable ]undefined remove (); };DocumentType includes ChildNode ;Element includes ChildNode ;CharacterData includes ChildNode ;
node .
before(...nodes)
-
Inserts nodes just before node, while replacing strings in nodes with equivalent
Text
nodes.Throws a "
HierarchyRequestError
"DOMException
if the constraints of the node tree are violated. node .
after(...nodes)
-
Inserts nodes just after node, while replacing strings in nodes with equivalent
Text
nodes.Throws a "
HierarchyRequestError
"DOMException
if the constraints of the node tree are violated. node .
replaceWith(...nodes)
-
Replaces node with nodes, while replacing strings in nodes with equivalent
Text
nodes.Throws a "
HierarchyRequestError
"DOMException
if the constraints of the node tree are violated. node .
remove()
- Removes node.
In all current engines.
Opera39+Edge79+
Edge (Legacy)17+IENone
Firefox for Android49+iOS Safari10+Chrome for Android54+Android WebView54+Samsung Internet6.0+Opera Mobile41+
The before(nodes)
method, when invoked,
must run these steps:
-
If parent is null, then return.
-
Let viablePreviousSibling be this’s first preceding sibling not in nodes, and null otherwise.
-
Let node be the result of converting nodes into a node, given nodes and this’s node document.
-
If viablePreviousSibling is null, set it to parent’s first child, and to viablePreviousSibling’s next sibling otherwise.
-
Pre-insert node into parent before viablePreviousSibling.
In all current engines.
Opera39+Edge79+
Edge (Legacy)17+IENone
Firefox for Android49+iOS Safari10+Chrome for Android54+Android WebView54+Samsung Internet6.0+Opera Mobile41+
The after(nodes)
method, when invoked,
must run these steps:
-
If parent is null, then return.
-
Let viableNextSibling be this’s first following sibling not in nodes, and null otherwise.
-
Let node be the result of converting nodes into a node, given nodes and this’s node document.
-
Pre-insert node into parent before viableNextSibling.
In all current engines.
Opera39+Edge79+
Edge (Legacy)17+IENone
Firefox for Android49+iOS SafariYesChrome for Android54+Android WebView54+Samsung Internet6.0+Opera Mobile41+
The replaceWith(nodes)
method, when
invoked, must run these steps:
-
If parent is null, then return.
-
Let viableNextSibling be this’s first following sibling not in nodes, and null otherwise.
-
Let node be the result of converting nodes into a node, given nodes and this’s node document.
-
If this’s parent is parent, replace this with node within parent.
This could have been inserted into node.
-
Otherwise, pre-insert node into parent before viableNextSibling.
In all current engines.
Opera15+Edge79+
Edge (Legacy)12+IENone
Firefox for Android23+iOS Safari7+Chrome for Android25+Android WebView37+Samsung Internet1.5+Opera Mobile14+
The remove()
method, when invoked, must run these
steps:
4.2.9. Mixin Slottable
In all current engines.
Opera40+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android63+iOS Safari10.3+Chrome for Android53+Android WebView53+Samsung Internet6.0+Opera Mobile41+
interface mixin {
Slottable readonly attribute HTMLSlotElement ?assignedSlot ; };Element includes Slottable ;Text includes Slottable ;
In all current engines.
Opera40+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android63+iOS Safari10.3+Chrome for Android53+Android WebView53+Samsung Internet6.0+Opera Mobile41+
In all current engines.
Opera40+Edge79+
Edge (Legacy)18IENone
Firefox for AndroidYesiOS Safari10.3+Chrome for Android53+Android WebView53+Samsung Internet6.0+Opera Mobile41+
The assignedSlot
attribute’s getter must return the result of find a slot given this and with the open flag set.
4.2.10. Old-style collections: NodeList
and HTMLCollection
A collection is an object that represents a list of nodes. A collection can be either live or static. Unless otherwise stated, a collection must be live.
If a collection is live, then the attributes and methods on that object must operate on the actual underlying data, not a snapshot of the data.
When a collection is created, a filter and a root are associated with it.
The collection then represents a view of the subtree rooted at the collection’s root, containing only nodes that match the given filter. The view is linear. In the absence of specific requirements to the contrary, the nodes within the collection must be sorted in tree order.
4.2.10.1. Interface NodeList
In all current engines.
Opera8+Edge79+
Edge (Legacy)12+IE6+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
A NodeList
object is a collection of nodes.
[Exposed =Window ]interface {
NodeList getter Node ?item (unsigned long );
index readonly attribute unsigned long length ;iterable <Node >; };
- collection .
length
- Returns the number of nodes in the collection.
- element = collection .
item(index)
- element = collection[index]
- Returns the node with index index from the collection. The nodes are sorted in tree order.
The object’s supported property indices are the numbers in the range zero to one less than the number of nodes represented by the collection. If there are no such elements, then there are no supported property indices.
In all current engines.
OperaYesEdge79+
Edge (Legacy)12+IE6+
Firefox for Android4+iOS SafariYesChrome for AndroidYesAndroid WebViewYesSamsung InternetYesOpera MobileYes
The length
attribute must return the number of nodes represented by the collection.
In all current engines.
OperaYesEdge79+
Edge (Legacy)12+IE6+
Firefox for Android4+iOS Safari1+Chrome for AndroidYesAndroid WebViewYesSamsung InternetYesOpera MobileYes
The item(index)
method must return the indexth node in the collection. If there is no indexth node in the collection, then the method must return
null.
4.2.10.2. Interface HTMLCollection
In all current engines.
Opera8+Edge79+
Edge (Legacy)12+IE8+
Firefox for Android4+iOS Safari3.2+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
[Exposed =Window ,LegacyUnenumerableNamedProperties ]interface {
HTMLCollection readonly attribute unsigned long length ;getter Element ?item (unsigned long );
index getter Element ?(
namedItem DOMString ); };
name
An HTMLCollection
object is a collection of elements.
HTMLCollection
is a historical artifact we cannot rid the web of.
While developers are of course welcome to keep using it, new API standard designers ought not to use
it (use sequence<T>
in IDL instead).
- collection .
length
- Returns the number of elements in the collection.
- element = collection .
item(index)
- element = collection[index]
- Returns the element with index index from the collection. The elements are sorted in tree order.
- element = collection .
namedItem(name)
- element = collection[name]
- Returns the first element with ID or name name from the collection.
The object’s supported property indices are the numbers in the range zero to one less than the number of elements represented by the collection. If there are no such elements, then there are no supported property indices.
The length
attribute’s getter must return
the number of nodes represented by the collection.
The item(index)
method, when
invoked, must return the indexth element in the collection. If there is no indexth element in the collection, then the method must return null.
The supported property names are the values from the list returned by these steps:
-
Let result be an empty list.
-
For each element represented by the collection, in tree order:
-
If element has an ID which is not in result, append element’s ID to result.
-
If element is in the HTML namespace and has a
name
attribute whose value is neither the empty string nor is in result, append element’sname
attribute value to result.
-
-
Return result.
The namedItem(key)
method, when
invoked, must run these steps:
-
If key is the empty string, return null.
-
Return the first element in the collection for which at least one of the following is true:
- it has an ID which is key;
- it is in the HTML namespace and has a
name
attribute whose value is key;
or null if there is no such element.
4.3. Mutation observers
HTMLSlotElement/slotchange_event
In all current engines.
Opera40+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android63+iOS Safari10.3+Chrome for Android53+Android WebView53+Samsung Internet6.0+Opera Mobile41+
Each similar-origin window agent has a mutation observer microtask queued (a boolean), which is initially false. [HTML]
Each similar-origin window agent also has mutation observers (a set of zero or more MutationObserver
objects), which is initially empty.
To queue a mutation observer microtask, run these steps:
-
If the surrounding agent’s mutation observer microtask queued is true, then return.
-
Set the surrounding agent’s mutation observer microtask queued to true.
To notify mutation observers, run these steps:
-
Set the surrounding agent’s mutation observer microtask queued to false.
-
Let notifySet be a clone of the surrounding agent’s mutation observers.
-
Let signalSet be a clone of the surrounding agent’s signal slots.
-
Empty the surrounding agent’s signal slots.
-
For each mo of notifySet:
-
Let records be a clone of mo’s record queue.
-
Empty mo’s record queue.
-
For each node of mo’s node list, remove all transient registered observers whose observer is mo from node’s registered observer list.
-
If records is not empty, then invoke mo’s callback with « records, mo », and mo. If this throws an exception, catch it, and report the exception.
-
-
For each slot of signalSet, fire an event named
slotchange
, with itsbubbles
attribute set to true, at slot.
Each node has a registered observer list (a list of zero or more registered observers), which is initially empty.
A registered observer consists of an observer (a MutationObserver
object) and options (a MutationObserverInit
dictionary).
A transient registered observer is a registered observer that also consists of a source (a registered observer).
Transient registered observers are used to track mutations within
a given node’s descendants after node has been removed so
they do not get lost when subtree
is set to true on node’s parent.
4.3.1. Interface MutationObserver
In all current engines.
Opera15+Edge79+
Edge (Legacy)12+IE11
Firefox for Android14+iOS Safari7+Chrome for Android26+Android WebView37+Samsung Internet1.5+Opera Mobile14+
MutationObserverInit/attributeFilter
In all current engines.
Opera15+Edge79+
Edge (Legacy)12+IE11
Firefox for Android14+iOS Safari7+Chrome for Android26+Samsung Internet1.5+Opera Mobile14+
MutationObserverInit/attributeOldValue
In all current engines.
Opera15+Edge79+
Edge (Legacy)12+IE11
Firefox for Android14+iOS Safari7+Chrome for Android26+Samsung Internet1.5+Opera Mobile14+
MutationObserverInit/attributes
In all current engines.
Opera15+Edge79+
Edge (Legacy)12+IE11
Firefox for Android14+iOS Safari7+Chrome for Android26+Samsung Internet1.5+Opera Mobile14+
MutationObserverInit/characterData
In all current engines.
Opera15+Edge79+
Edge (Legacy)12+IE11
Firefox for Android14+iOS Safari7+Chrome for Android26+Samsung Internet1.5+Opera Mobile14+
MutationObserverInit/characterDataOldValue
In all current engines.
Opera15+Edge79+
Edge (Legacy)12+IE11
Firefox for Android14+iOS Safari7+Chrome for Android26+Samsung Internet1.5+Opera Mobile14+
MutationObserverInit/childList
In all current engines.
Opera15+Edge79+
Edge (Legacy)12+IE11
Firefox for Android14+iOS Safari7+Chrome for Android26+Samsung Internet1.5+Opera Mobile14+
In all current engines.
Opera15+Edge79+
Edge (Legacy)12+IE11
Firefox for Android14+iOS Safari7+Chrome for Android26+Samsung Internet1.5+Opera Mobile14+
In all current engines.
Opera15+Edge79+
Edge (Legacy)12+IE11
Firefox for Android14+iOS Safari7+Chrome for Android26+Samsung Internet1.5+Opera Mobile14+
[Exposed =Window ]interface {
MutationObserver constructor (MutationCallback );
callback undefined observe (Node ,
target optional MutationObserverInit = {});
options undefined disconnect ();sequence <MutationRecord >takeRecords (); };callback =
MutationCallback undefined (sequence <MutationRecord >,
mutations MutationObserver );
observer dictionary {
MutationObserverInit boolean =
childList false ;boolean ;
attributes boolean ;
characterData boolean =
subtree false ;boolean ;
attributeOldValue boolean ;
characterDataOldValue sequence <DOMString >; };
attributeFilter
A MutationObserver
object can be used to observe mutations to the tree of nodes.
Each MutationObserver
object has these associated concepts:
- A callback set on creation.
- A node list (a list of nodes), which is initially empty.
- A record queue (a queue of zero or more
MutationRecord
objects), which is initially empty.
observer = new
MutationObserver(callback)
- Constructs a
MutationObserver
object and sets its callback to callback. The callback is invoked with a list ofMutationRecord
objects as first argument and the constructedMutationObserver
object as second argument. It is invoked after nodes registered with theobserve()
method, are mutated. observer .
observe(target, options)
-
Instructs the user agent to observe a given target (a node) and report any mutations based on
the criteria given by options (an object).
The options argument allows for setting mutation observation options via object members. These are the object members that can be used:
childList
- Set to true if mutations to target’s children are to be observed.
attributes
- Set to true if mutations to target’s attributes are to be observed. Can be omitted if
attributeOldValue
orattributeFilter
is specified. characterData
- Set to true if mutations to target’s data are to be observed. Can be omitted if
characterDataOldValue
is specified. subtree
- Set to true if mutations to not just target, but also target’s descendants are to be observed.
attributeOldValue
- Set to true if
attributes
is true or omitted and target’s attribute value before the mutation needs to be recorded. characterDataOldValue
- Set to true if
characterData
is set to true or omitted and target’s data before the mutation needs to be recorded. attributeFilter
- Set to a list of attribute local names (without namespace) if not all attribute mutations need to be
observed and
attributes
is true or omitted.
observer .
disconnect()
- Stops observer from observing any mutations. Until the
observe()
method is used again, observer’s callback will not be invoked. observer .
takeRecords()
- Empties the record queue and returns what was in there.
MutationObserver/MutationObserver
In all current engines.
Opera15+Edge79+
Edge (Legacy)12+IE11
Firefox for Android14+iOS Safari7+Chrome for Android26+Android WebViewYesSamsung Internet1.5+Opera Mobile14+
The MutationObserver(callback)
constructor, when invoked, must run these steps:
-
Let mo be a new
MutationObserver
object whose callback is callback. -
Append mo to mo’s relevant agent’s mutation observers.
-
Return mo.
In all current engines.
Opera15+Edge79+
Edge (Legacy)12+IE11
Firefox for Android14+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+
The observe(target, options)
method, when invoked, must run these steps:
-
If either options’s
attributeOldValue
orattributeFilter
is present and options’sattributes
is omitted, then set options’sattributes
to true. -
If options’s
characterDataOldValue
is present and options’scharacterData
is omitted, then set options’scharacterData
to true. -
If none of options’s
childList
,attributes
, andcharacterData
is true, then throw aTypeError
. -
If options’s
attributeOldValue
is true and options’sattributes
is false, then throw aTypeError
. -
If options’s
attributeFilter
is present and options’sattributes
is false, then throw aTypeError
. -
If options’s
characterDataOldValue
is true and options’scharacterData
is false, then throw aTypeError
. -
For each registered of target’s registered observer list, if registered’s observer is this:
-
For each node of this’s node list, remove all transient registered observers whose source is registered from node’s registered observer list.
-
Set registered’s options to options.
-
-
Otherwise:
-
Append a new registered observer whose observer is this and options is options to target’s registered observer list.
-
In all current engines.
Opera15+Edge79+
Edge (Legacy)12+IE11
Firefox for Android14+iOS Safari6+Chrome for Android18+Android WebViewYesSamsung Internet1.0+Opera Mobile14+
The disconnect()
method, when invoked, must
run these steps:
-
For each node of this’s node list, remove any registered observer from node’s registered observer list for which this is the observer.
In all current engines.
Opera15+Edge79+
Edge (Legacy)12+IE11
Firefox for Android14+iOS Safari6+Chrome for Android18+Android WebViewYesSamsung Internet1.0+Opera Mobile14+
The takeRecords()
method, when invoked, must
run these steps:
-
Let records be a clone of this’s record queue.
-
Return records.
4.3.2. Queuing a mutation record
To queue a mutation record of type for target with name, namespace, oldValue, addedNodes, removedNodes, previousSibling, and nextSibling, run these steps:
-
Let interestedObservers be an empty map.
-
Let nodes be the inclusive ancestors of target.
-
For each node in nodes, and then for each registered of node’s registered observer list:
-
Let options be registered’s options.
-
If none of the following are true
- node is not target and options’s
subtree
is false - type is "
attributes
" and options’sattributes
is not true - type is "
attributes
", options’sattributeFilter
is present, and options’sattributeFilter
does not contain name or namespace is non-null - type is "
characterData
" and options’scharacterData
is not true - type is "
childList
" and options’schildList
is false
then:
-
Let mo be registered’s observer.
-
If interestedObservers[mo] does not exist, then set interestedObservers[mo] to null.
-
If either type is "
attributes
" and options’sattributeOldValue
is true, or type is "characterData
" and options’scharacterDataOldValue
is true, then set interestedObservers[mo] to oldValue.
- node is not target and options’s
-
-
For each observer → mappedOldValue of interestedObservers:
-
Let record be a new
MutationRecord
object with itstype
set to type,target
set to target,attributeName
set to name,attributeNamespace
set to namespace,oldValue
set to mappedOldValue,addedNodes
set to addedNodes,removedNodes
set to removedNodes,previousSibling
set to previousSibling, andnextSibling
set to nextSibling. -
Enqueue record to observer’s record queue.
-
To queue a tree mutation record for target with addedNodes, removedNodes, previousSibling, and nextSibling, run these steps:
-
Assert: either addedNodes or removedNodes is not empty.
-
Queue a mutation record of "
childList
" for target with null, null, null, addedNodes, removedNodes, previousSibling, and nextSibling.
4.3.3. Interface MutationRecord
In all current engines.
OperaYesEdgeYes
Edge (Legacy)12+IE?
Firefox for AndroidYesiOS SafariYesChrome for AndroidYesAndroid WebViewYesSamsung InternetYesOpera MobileYes
[Exposed =Window ]interface {
MutationRecord readonly attribute DOMString type ; [SameObject ]readonly attribute Node target ; [SameObject ]readonly attribute NodeList addedNodes ; [SameObject ]readonly attribute NodeList removedNodes ;readonly attribute Node ?previousSibling ;readonly attribute Node ?nextSibling ;readonly attribute DOMString ?attributeName ;readonly attribute DOMString ?attributeNamespace ;readonly attribute DOMString ?oldValue ; };
record .
type
- Returns "
attributes
" if it was an attribute mutation. "characterData
" if it was a mutation to aCharacterData
node. And "childList
" if it was a mutation to the tree of nodes. record .
target
- Returns the node the mutation
affected, depending on the
type
. For "attributes
", it is the element whose attribute changed. For "characterData
", it is theCharacterData
node. For "childList
", it is the node whose children changed. record .
addedNodes
record .
removedNodes
- Return the nodes added and removed respectively.
record .
previousSibling
record .
nextSibling
- Return the previous and next sibling respectively of the added or removed nodes, and null otherwise.
record .
attributeName
- Returns the local name of the changed attribute, and null otherwise.
record .
attributeNamespace
- Returns the namespace of the changed attribute, and null otherwise.
record .
oldValue
- The return value depends on
type
. For "attributes
", it is the value of the changed attribute before the change. For "characterData
", it is the data of the changed node before the change. For "childList
", it is null.
The type
, target
, addedNodes
, removedNodes
, previousSibling
, nextSibling
, attributeName
, attributeNamespace
, and oldValue
attributes must return the values they were
initialized to.
4.3.4. Garbage collection
Nodes have a strong reference to registered observers in their registered observer list.
Registered observers in a node’s registered observer list have a weak reference to the node.
4.4. Interface Node
In all current engines.
Opera7+Edge79+
Edge (Legacy)12+IE5+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
[Exposed =Window ]interface :
Node EventTarget {const unsigned short ELEMENT_NODE = 1;const unsigned short ATTRIBUTE_NODE = 2;const unsigned short TEXT_NODE = 3;const unsigned short CDATA_SECTION_NODE = 4;const unsigned short = 5; // legacy
ENTITY_REFERENCE_NODE const unsigned short = 6; // legacy
ENTITY_NODE const unsigned short PROCESSING_INSTRUCTION_NODE = 7;const unsigned short COMMENT_NODE = 8;const unsigned short DOCUMENT_NODE = 9;const unsigned short DOCUMENT_TYPE_NODE = 10;const unsigned short DOCUMENT_FRAGMENT_NODE = 11;const unsigned short = 12; // legacy
NOTATION_NODE readonly attribute unsigned short nodeType ;readonly attribute DOMString nodeName ;readonly attribute USVString baseURI ;readonly attribute boolean isConnected ;readonly attribute Document ?ownerDocument ;Node getRootNode (optional GetRootNodeOptions = {});
options readonly attribute Node ?parentNode ;readonly attribute Element ?parentElement ;boolean hasChildNodes (); [SameObject ]readonly attribute NodeList childNodes ;readonly attribute Node ?firstChild ;readonly attribute Node ?lastChild ;readonly attribute Node ?previousSibling ;readonly attribute Node ?nextSibling ; [CEReactions ]attribute DOMString ?nodeValue ; [CEReactions ]attribute DOMString ?textContent ; [CEReactions ]undefined normalize (); [CEReactions ,NewObject ]Node cloneNode (optional boolean =
deep false );boolean isEqualNode (Node ?);
otherNode boolean isSameNode (Node ?); // legacy alias of ===
otherNode const unsigned short DOCUMENT_POSITION_DISCONNECTED = 0x01;const unsigned short DOCUMENT_POSITION_PRECEDING = 0x02;const unsigned short DOCUMENT_POSITION_FOLLOWING = 0x04;const unsigned short DOCUMENT_POSITION_CONTAINS = 0x08;const unsigned short DOCUMENT_POSITION_CONTAINED_BY = 0x10;const unsigned short DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 0x20;unsigned short compareDocumentPosition (Node );
other boolean contains (Node ?);
other DOMString ?lookupPrefix (DOMString ?);
namespace DOMString ?lookupNamespaceURI (DOMString ?);
prefix boolean isDefaultNamespace (DOMString ?); [
namespace CEReactions ]Node insertBefore (Node ,
node Node ?); [
child CEReactions ]Node appendChild (Node ); [
node CEReactions ]Node replaceChild (Node ,
node Node ); [
child CEReactions ]Node removeChild (Node ); };
child dictionary {
GetRootNodeOptions boolean =
composed false ; };
Node
is an abstract interface and does not exist as node. It
is used by all nodes (Document
, DocumentType
, DocumentFragment
, Element
, Text
, ProcessingInstruction
, and Comment
).
Each node has an associated node document, set upon creation, that is a document.
A node’s node document can be changed by the adopt algorithm.
A node’s get the parent algorithm, given an event, returns the node’s assigned slot, if node is assigned, and node’s parent otherwise.
Each node also has a registered observer list.
node .
nodeType
-
Returns the type of node, represented by a number from the following list:
(1)Node
.ELEMENT_NODE
- node is an element.
(3)Node
.TEXT_NODE
- node is a
Text
node.
(4)Node
.CDATA_SECTION_NODE
- node is a
CDATASection
node.
(7)Node
.PROCESSING_INSTRUCTION_NODE
- node is a
ProcessingInstruction
node.
(8)Node
.COMMENT_NODE
- node is a
Comment
node.
(9)Node
.DOCUMENT_NODE
- node is a document.
(10)Node
.DOCUMENT_TYPE_NODE
- node is a doctype.
(11)Node
.DOCUMENT_FRAGMENT_NODE
- node is a
DocumentFragment
node.
node .
nodeName
-
Returns a string appropriate for the type of node, as
follows:
Element
- Its HTML-uppercased qualified name.
Attr
- Its qualified name.
Text
- "
#text
". CDATASection
- "
#cdata-section
". ProcessingInstruction
- Its target.
Comment
- "
#comment
". Document
- "
#document
". DocumentType
- Its name.
DocumentFragment
- "
#document-fragment
".
In all current engines.
Opera7+Edge79+
Edge (Legacy)12+IE6+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
The nodeType
attribute’s getter, when invoked, must return
the first matching statement, switching on this:
Element
ELEMENT_NODE
(1)Attr
ATTRIBUTE_NODE
(2);Text
TEXT_NODE
(3);CDATASection
CDATA_SECTION_NODE
(4);ProcessingInstruction
PROCESSING_INSTRUCTION_NODE
(7);Comment
COMMENT_NODE
(8);Document
DOCUMENT_NODE
(9);DocumentType
DOCUMENT_TYPE_NODE
(10);DocumentFragment
DOCUMENT_FRAGMENT_NODE
(11).
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IE6+
Firefox for Android4+iOS Safari7+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+
The nodeName
attribute’s getter, when invoked, must return the
first matching statement, switching on this:
Element
- Its HTML-uppercased qualified name.
Attr
- Its qualified name.
Text
- "
#text
". CDATASection
- "
#cdata-section
". ProcessingInstruction
- Its target.
Comment
- "
#comment
". Document
- "
#document
". DocumentType
- Its name.
DocumentFragment
- "
#document-fragment
".
node .
baseURI
- Returns node’s node document’s document base URL.
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IENone
Firefox for Android4+iOS Safari7+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+
The baseURI
attribute’s getter must return node document’s document base URL, serialized.
node .
isConnected
-
Returns true if node is connected and false otherwise.
node .
ownerDocument
- Returns the node document. Returns null for documents.
node .
getRootNode()
- Returns node’s root.
node . getRootNode({ composed:true })
- Returns node’s shadow-including root.
node .
parentNode
- Returns the parent.
node .
parentElement
- Returns the parent element.
node .
hasChildNodes()
- Returns whether node has children.
node .
childNodes
- Returns the children.
node .
firstChild
- Returns the first child.
node .
lastChild
- Returns the last child.
node .
previousSibling
- Returns the previous sibling.
node .
nextSibling
- Returns the next sibling.
In all current engines.
Opera38+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android45+iOS Safari10+Chrome for Android51+Android WebView51+Samsung Internet6.0+Opera Mobile41+
The isConnected
attribute’s getter must return true,
if this is connected, and false otherwise.
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IE6+
Firefox for Android9+iOS Safari7+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+
The ownerDocument
attribute’s getter must return null,
if this is a document, and this’s node document otherwise.
The node document of a document is that document itself. All nodes have a node document at all times.
In all current engines.
Opera41+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android53+iOS Safari10.3+Chrome for Android54+Android WebView54+Samsung Internet6.0+Opera Mobile41+
The getRootNode(options)
method, when invoked,
must return this’s shadow-including root if options’s composed
is true, and this’s root otherwise.
In all current engines.
Opera7+Edge79+
Edge (Legacy)12+IE5.5+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
The parentNode
attribute’s getter must return this’s parent.
In all current engines.
Opera7+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android9+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
The parentElement
attribute’s getter must return this’s parent element.
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IE6+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+
The hasChildNodes()
method, when invoked, must return
true if this has children, and false otherwise.
In all current engines.
Opera7+Edge79+
Edge (Legacy)12+IE5+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
The childNodes
attribute’s getter must return a NodeList
rooted at this matching only children.
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IE6+
Firefox for Android4+iOS Safari7+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+
The firstChild
attribute’s getter must return this’s first child.
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IE6+
Firefox for Android45+iOS Safari7+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+
The lastChild
attribute’s getter must return this’s last child.
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IE5.5+
Firefox for Android4+iOS Safari7+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+
The previousSibling
attribute’s getter must return this’s previous sibling.
In all current engines.
Opera7+Edge79+
Edge (Legacy)12+IE5.5+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
The nextSibling
attribute’s getter must return this’s next sibling.
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IE6+
Firefox for Android4+iOS Safari7+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+
The nodeValue
attribute
must return the following, depending on this:
Attr
- this’s value.
Text
ProcessingInstruction
Comment
- this’s data.
- Any other node
- Null.
The nodeValue
attribute must,
on setting, if the new value is null, act as if it was the empty string
instead, and then do as described below, depending on this:
Attr
-
Set an existing attribute value with this and new value.
Text
ProcessingInstruction
Comment
-
Replace data with node this, offset 0, count this’s length, and data new value.
- Any other node
-
Do nothing.
In all current engines.
Opera9+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
The textContent
attribute’s getter must return the
following, switching on this:
DocumentFragment
Element
- The descendant text content of this.
Attr
- this’s value.
Text
ProcessingInstruction
Comment
- this’s data.
- Any other node
- Null.
To string replace all with a string string within a node parent, run these steps:
-
Let node be null.
-
If string is not the empty string, then set node to a new
Text
node whose data is string and node document is parent’s node document. -
Replace all with node within parent.
The textContent
attribute’s setter must, if the given value is null, act as if it was
the empty string instead, and then do as described below, switching on this:
DocumentFragment
Element
-
String replace all with the given value within this.
Attr
-
Set an existing attribute value with this and new value.
Text
ProcessingInstruction
Comment
-
Replace data with node this, offset 0, count this’s length, and data the given value.
- Any other node
-
Do nothing.
node .
normalize()
- Removes empty exclusive
Text
nodes and concatenates the data of remaining contiguous exclusiveText
nodes into the first of their nodes.
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+
The normalize()
method, when invoked, must run these
steps for each descendant exclusive Text
node node of this:
- Let length be node’s length.
- If length is zero, then remove node and continue with the
next exclusive
Text
node, if any. - Let data be the concatenation of the data of node’s contiguous exclusive
Text
nodes (excluding itself), in tree order. - Replace data with node node, offset length, count 0, and data data.
- Let currentNode be node’s next sibling.
-
While currentNode is an exclusive
Text
node:-
For each live range whose start node is currentNode, add length to its start offset and set its start node to node.
-
For each live range whose end node is currentNode, add length to its end offset and set its end node to node.
-
For each live range whose start node is currentNode’s parent and start offset is currentNode’s index, set its start node to node and its start offset to length.
-
For each live range whose end node is currentNode’s parent and end offset is currentNode’s index, set its end node to node and its end offset to length.
-
Add currentNode’s length to length.
-
Set currentNode to its next sibling.
-
- Remove node’s contiguous exclusive
Text
nodes (excluding itself), in tree order.
node . cloneNode([deep = false])
- Returns a copy of node. If deep is true, the copy also includes the node’s descendants.
node .
isEqualNode(otherNode)
- Returns whether node and otherNode have the same properties.
Specifications may define cloning steps for all or some nodes. The algorithm is passed copy, node, document, and an optional clone children flag, as indicated in the clone algorithm.
HTML defines cloning steps for script
and input
elements. SVG ought to do the same for its script
elements, but does not call this out
at the moment.
To clone a node, with an optional document and clone children flag, run these steps:
-
If document is not given, let document be node’s node document.
-
If node is an element, then:
-
Let copy be the result of creating an element, given document, node’s local name, node’s namespace, node’s namespace prefix, and node’s
is
value, with the synchronous custom elements flag unset. -
For each attribute in node’s attribute list:
-
-
Otherwise, let copy be a node that implements the same interfaces as node, and fulfills these additional requirements, switching on node:
Document
-
Set copy’s encoding, content type, URL, origin, type, and mode, to those of node.
DocumentType
-
Set copy’s name, public ID, and system ID, to those of node.
Attr
-
Set copy’s namespace, namespace prefix, local name, and value, to those of node.
Text
Comment
- Set copy’s data, to that of node.
ProcessingInstruction
- Set copy’s target and data to those of node.
- Any other node
- —
-
Set copy’s node document and document to copy, if copy is a document, and set copy’s node document to document otherwise.
- Run any cloning steps defined for node in other applicable specifications and pass copy, node, document and the clone children flag if set, as parameters.
- If the clone children flag is set, clone all the children of node and append them to copy, with document as specified and the clone children flag being set.
- Return copy.
In all current engines.
Opera7+Edge79+
Edge (Legacy)12+IE6+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
The cloneNode(deep)
method, when
invoked, must run these steps:
-
If this is a shadow root, then throw a "
NotSupportedError
"DOMException
. -
Return a clone of this, with the clone children flag set if deep is true.
A node A equals a node B if all of the following conditions are true:
- A and B’s
nodeType
attribute value is identical. -
The following are also equal, depending on A:
DocumentType
- Its name, public ID, and system ID.
Element
- Its namespace, namespace prefix, local name, and its attribute list’s size.
Attr
- Its namespace, local name, and value.
ProcessingInstruction
- Its target and data.
Text
Comment
- Its data.
- Any other node
- —
- If A is an element, each attribute in its attribute list has an attribute that equals an attribute in B’s attribute list.
- A and B have the same number of children.
- Each child of A equals the child of B at the identical index.
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+
The isEqualNode(otherNode)
method, when
invoked, must return true if otherNode is non-null and this equals otherNode, and false otherwise.
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android48+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+
The isSameNode(otherNode)
method, when
invoked, must return true if otherNode is this, and false otherwise.
node .
compareDocumentPosition(other)
-
Returns a bitmask indicating the position of other relative to node. These are the bits that can be set:
(1)Node
.DOCUMENT_POSITION_DISCONNECTED
- Set when node and other are not in the same tree.
(2)Node
.DOCUMENT_POSITION_PRECEDING
- Set when other is preceding node.
(4)Node
.DOCUMENT_POSITION_FOLLOWING
- Set when other is following node.
(8)Node
.DOCUMENT_POSITION_CONTAINS
- Set when other is an ancestor of node.
(16, 10 in hexadecimal)Node
.DOCUMENT_POSITION_CONTAINED_BY
- Set when other is a descendant of node.
node .
contains(other)
- Returns true if other is an inclusive descendant of node, and false otherwise.
These are the constants compareDocumentPosition()
returns as mask:
DOCUMENT_POSITION_DISCONNECTED
(1);DOCUMENT_POSITION_PRECEDING
(2);DOCUMENT_POSITION_FOLLOWING
(4);DOCUMENT_POSITION_CONTAINS
(8);DOCUMENT_POSITION_CONTAINED_BY
(16, 10 in hexadecimal);DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC
(32, 20 in hexadecimal).
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android9+iOS SafariYesChrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+
The compareDocumentPosition(other)
method,
when invoked, must run these steps:
-
If this is other, then return zero.
-
Let node1 be other and node2 be this.
-
Let attr1 and attr2 be null.
-
If node1 is an attribute, then set attr1 to node1 and node1 to attr1’s element.
-
If node2 is an attribute, then:
-
Set attr2 to node2 and node2 to attr2’s element.
-
If attr1 and node1 are non-null, and node2 is node1, then:
-
For each attr in node2’s attribute list:
-
If attr equals attr1, then return the result of adding
DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC
andDOCUMENT_POSITION_PRECEDING
. -
If attr equals attr2, then return the result of adding
DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC
andDOCUMENT_POSITION_FOLLOWING
.
-
-
-
-
If node1 or node2 is null, or node1’s root is not node2’s root, then return the result of adding
DOCUMENT_POSITION_DISCONNECTED
,DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC
, and eitherDOCUMENT_POSITION_PRECEDING
orDOCUMENT_POSITION_FOLLOWING
, with the constraint that this is to be consistent, together.Whether to return
DOCUMENT_POSITION_PRECEDING
orDOCUMENT_POSITION_FOLLOWING
is typically implemented via pointer comparison. In JavaScript implementations a cachedMath
value can be used.. random() -
If node1 is an ancestor of node2 and attr1 is null, or node1 is node2 and attr2 is non-null, then return the result of adding
DOCUMENT_POSITION_CONTAINS
toDOCUMENT_POSITION_PRECEDING
. -
If node1 is a descendant of node2 and attr2 is null, or node1 is node2 and attr1 is non-null, then return the result of adding
DOCUMENT_POSITION_CONTAINED_BY
toDOCUMENT_POSITION_FOLLOWING
. -
If node1 is preceding node2, then return
DOCUMENT_POSITION_PRECEDING
.Due to the way attributes are handled in this algorithm this results in a node’s attributes counting as preceding that node’s children, despite attributes not participating in a tree.
-
Return
DOCUMENT_POSITION_FOLLOWING
.
In all current engines.
Opera7+Edge79+
Edge (Legacy)12+IENone
Firefox for Android9+iOS Safari1+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile10.1+
The contains(other)
method, when invoked, must
return true if other is an inclusive descendant of this, and false
otherwise (including when other is null).
To locate a namespace prefix for an element using namespace, run these steps:
-
If element’s namespace is namespace and its namespace prefix is non-null, then return its namespace prefix.
-
If element has an attribute whose namespace prefix is "
xmlns
" and value is namespace, then return element’s first such attribute’s local name. -
If element’s parent element is not null, then return the result of running locate a namespace prefix on that element using namespace.
-
Return null.
To locate a namespace for a node using prefix, switch on node:
Element
-
-
If its namespace is non-null and its namespace prefix is prefix, then return namespace.
-
If it has an attribute whose namespace is the XMLNS namespace, namespace prefix is "
xmlns
", and local name is prefix, or if prefix is null and it has an attribute whose namespace is the XMLNS namespace, namespace prefix is null, and local name is "xmlns
", then return its value if it is not the empty string, and null otherwise. -
If its parent element is null, then return null.
-
Return the result of running locate a namespace on its parent element using prefix.
-
Document
-
-
If its document element is null, then return null.
-
Return the result of running locate a namespace on its document element using prefix.
-
DocumentType
DocumentFragment
-
Return null.
Attr
-
-
If its element is null, then return null.
-
Return the result of running locate a namespace on its element using prefix.
-
- Any other node
-
-
If its parent element is null, then return null.
-
Return the result of running locate a namespace on its parent element using prefix.
-
The lookupPrefix(namespace)
method, when
invoked, must run these steps:
-
If namespace is null or the empty string, then return null.
-
Switch on this:
Element
-
Return the result of locating a namespace prefix for it using namespace.
Document
-
Return the result of locating a namespace prefix for its document element, if its document element is non-null, and null otherwise.
DocumentType
DocumentFragment
-
Return null.
Attr
-
Return the result of locating a namespace prefix for its element, if its element is non-null, and null otherwise.
- Any other node
-
Return the result of locating a namespace prefix for its parent element, if its parent element is non-null, and null otherwise.
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+
The lookupNamespaceURI(prefix)
method, when
invoked, must run these steps:
-
If prefix is the empty string, then set it to null.
-
Return the result of running locate a namespace for this using prefix.
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+
The isDefaultNamespace(namespace)
method, when
invoked, must run these steps:
-
If namespace is the empty string, then set it to null.
-
Let defaultNamespace be the result of running locate a namespace for this using null.
-
Return true if defaultNamespace is the same as namespace, and false otherwise.
In all current engines.
Opera7+Edge79+
Edge (Legacy)12+IE6+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
The insertBefore(node, child)
method, when invoked, must return the result of pre-inserting node into this before child.
In all current engines.
Opera7+Edge79+
Edge (Legacy)12+IE5+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
The appendChild(node)
method, when invoked,
must return the result of appending node to this.
In all current engines.
Opera7+Edge79+
Edge (Legacy)12+IE6+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
The replaceChild(node, child)
method, when invoked, must return the result of replacing child with node within this.
In all current engines.
Opera7+Edge79+
Edge (Legacy)12+IE5+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
The removeChild(child)
method, when invoked,
must return the result of pre-removing child from this.
The list of elements with qualified name qualifiedName for a node root is the HTMLCollection
returned by the following algorithm:
-
If qualifiedName is "
*
" (U+002A), return aHTMLCollection
rooted at root, whose filter matches only descendant elements. -
Otherwise, if root’s node document is an HTML document, return a
HTMLCollection
rooted at root, whose filter matches the following descendant elements:-
Whose namespace is the HTML namespace and whose qualified name is qualifiedName, in ASCII lowercase.
-
Whose namespace is not the HTML namespace and whose qualified name is qualifiedName.
-
-
Otherwise, return a
HTMLCollection
rooted at root, whose filter matches descendant elements whose qualified name is qualifiedName.
When invoked with the same argument, and as long as root’s node document’s type has not changed, the same HTMLCollection
object may be returned as returned by an earlier call.
The list of elements with namespace namespace and local name localName for a node root is the HTMLCollection
returned by the following algorithm:
- If namespace is the empty string, set it to null.
- If both namespace and localName are "
*
" (U+002A), return aHTMLCollection
rooted at root, whose filter matches descendant elements. - Otherwise, if namespace is "
*
" (U+002A), return aHTMLCollection
rooted at root, whose filter matches descendant elements whose local name is localName. - Otherwise, if localName is "
*
" (U+002A), return aHTMLCollection
rooted at root, whose filter matches descendant elements whose namespace is namespace. - Otherwise, return a
HTMLCollection
rooted at root, whose filter matches descendant elements whose namespace is namespace and local name is localName.
When invoked with the same arguments, the same HTMLCollection
object may be returned as returned by an earlier call.
The list of elements with class names classNames for a node root is the HTMLCollection
returned by the following algorithm:
- Let classes be the result of running the ordered set parser on classNames.
- If classes is the empty set, return an empty
HTMLCollection
. -
Return a
HTMLCollection
rooted at root, whose filter matches descendant elements that have all their classes in classes.The comparisons for the classes must be done in an ASCII case-insensitive manner if root’s node document’s mode is "
quirks
", and in an identical to manner otherwise.
When invoked with the same argument, the same HTMLCollection
object may be returned as returned by an earlier call.
4.5. Interface Document
In all current engines.
Opera3+Edge79+
Edge (Legacy)12+IE4+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
In all current engines.
Opera21+Edge79+
Edge (Legacy)18IENone
Firefox for Android4+iOS Safari10+Chrome for Android34+Android WebView37+Samsung Internet2.0+Opera Mobile21+
[Exposed =Window ]interface :
Document Node {constructor (); [SameObject ]readonly attribute DOMImplementation implementation ;readonly attribute USVString URL ;readonly attribute USVString documentURI ;readonly attribute DOMString compatMode ;readonly attribute DOMString characterSet ;readonly attribute DOMString charset ; // legacy alias of .characterSetreadonly attribute DOMString inputEncoding ; // legacy alias of .characterSetreadonly attribute DOMString contentType ;readonly attribute DocumentType ?doctype ;readonly attribute Element ?documentElement ;HTMLCollection getElementsByTagName (DOMString );
qualifiedName HTMLCollection getElementsByTagNameNS (DOMString ?,
namespace DOMString );
localName HTMLCollection getElementsByClassName (DOMString ); [
classNames CEReactions ,NewObject ]Element createElement (DOMString ,
localName optional (DOMString or ElementCreationOptions )= {}); [
options CEReactions ,NewObject ]Element createElementNS (DOMString ?,
namespace DOMString ,
qualifiedName optional (DOMString or ElementCreationOptions )= {}); [
options NewObject ]DocumentFragment createDocumentFragment (); [NewObject ]Text createTextNode (DOMString ); [
data NewObject ]CDATASection createCDATASection (DOMString ); [
data NewObject ]Comment createComment (DOMString ); [
data NewObject ]ProcessingInstruction createProcessingInstruction (DOMString ,
target DOMString ); [
data CEReactions ,NewObject ]Node importNode (Node ,
node optional boolean =
deep false ); [CEReactions ]Node adoptNode (Node ); [
node NewObject ]Attr createAttribute (DOMString ); [
localName NewObject ]Attr createAttributeNS (DOMString ?,
namespace DOMString ); [
qualifiedName NewObject ]Event createEvent (DOMString ); // legacy [
interface NewObject ]Range createRange (); // NodeFilter.SHOW_ALL = 0xFFFFFFFF [NewObject ]NodeIterator createNodeIterator (Node ,
root optional unsigned long = 0xFFFFFFFF,
whatToShow optional NodeFilter ?=
filter null ); [NewObject ]TreeWalker createTreeWalker (Node ,
root optional unsigned long = 0xFFFFFFFF,
whatToShow optional NodeFilter ?=
filter null ); }; [Exposed =Window ]interface :
XMLDocument Document {};dictionary {
ElementCreationOptions DOMString ; };
is
Document
nodes are simply
known as documents.
Each document has an associated encoding (an encoding), content type (a string), URL (a URL), origin (an origin), type ("xml
" or "html
"), and mode ("no-quirks
", "quirks
", or "limited-quirks
"). [ENCODING] [URL] [HTML]
Unless stated otherwise, a document’s encoding is the utf-8 encoding, content type is
"application/xml
", URL is "about:blank
", origin is an opaque origin, type is "xml
", and its mode is "no-quirks
".
A document is said to be an XML document if its type is "xml
", and an HTML document otherwise. Whether a document is an HTML document or an XML document affects the behavior of certain APIs.
A document is said to be in no-quirks mode if its mode is "no-quirks
", quirks mode if its mode is "quirks
", and limited-quirks mode if its mode is "limited-quirks
".
The mode is only ever changed from the default for documents created
by the HTML parser based on the presence, absence, or value of the DOCTYPE string, and by a
new browsing context (initial "about:blank
"). [HTML]
No-quirks mode was originally known as "standards mode" and limited-quirks mode was once known as "almost standards mode". They have been renamed because their details are now defined by standards. (And because Ian Hickson vetoed their original names on the basis that they are nonsensical.)
A document’s get the parent algorithm, given an event, returns
null if event’s type
attribute value is "load
" or document does not have a browsing context, and the document’s relevant global object otherwise.
document = new
Document()
- Returns a new document.
document .
implementation
- Returns document’s
DOMImplementation
object. document .
URL
document .
documentURI
- Returns document’s URL.
document .
compatMode
- Returns the string "
BackCompat
" if document’s mode is "quirks
", and "CSS1Compat
" otherwise. document .
characterSet
- Returns document’s encoding.
document .
contentType
- Returns document’s content type.
In all current engines.
Opera47+Edge79+
Edge (Legacy)17+IENone
Firefox for Android20+iOS Safari6.1+Chrome for Android60+Android WebView60+Samsung Internet8.0+Opera Mobile44+
The Document()
constructor, when invoked, must
return a new document whose origin is the origin of current global object’s associated Document
. [HTML]
Unlike createDocument()
, this constructor does not
return an XMLDocument
object, but a document (Document
object).
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IE6+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+
The implementation
attribute’s getter must return the DOMImplementation
object that is associated with the document.
In all current engines.
Opera3+Edge79+
Edge (Legacy)12+IE4+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)17+IENone
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+
The URL
attribute’s getter and documentURI
attribute’s getter must return the URL, serialized.
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IE6+
Firefox for Android4+iOS Safari2+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+
The compatMode
attribute’s getter must
return "BackCompat
" if this’s mode is
"quirks
", and "CSS1Compat
" otherwise.
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera MobileYes
The characterSet
attribute’s getter, charset
attribute’s getter, and inputEncoding
attribute’s getter, must return this’s encoding’s name.
In all current engines.
Opera23+Edge79+
Edge (Legacy)17+IENone
Firefox for Android4+iOS Safari9+Chrome for Android36+Android WebView37+Samsung Internet3.0+Opera Mobile24+
The contentType
attribute’s getter must return the content type.
- document .
doctype
- Returns the doctype or null if there is none.
- document .
documentElement
- Returns the document element.
- collection = document .
getElementsByTagName(qualifiedName)
-
If qualifiedName is "
*
" returns aHTMLCollection
of all descendant elements.Otherwise, returns a
HTMLCollection
of all descendant elements whose qualified name is qualifiedName. (Matches case-insensitively against elements in the HTML namespace within an HTML document.) - collection = document .
getElementsByTagNameNS(namespace, localName)
-
If namespace and localName are
"
*
" returns aHTMLCollection
of all descendant elements.If only namespace is "
*
" returns aHTMLCollection
of all descendant elements whose local name is localName.If only localName is "
*
" returns aHTMLCollection
of all descendant elements whose namespace is namespace.Otherwise, returns a
HTMLCollection
of all descendant elements whose namespace is namespace and local name is localName. - collection = document .
getElementsByClassName(classNames)
- collection = element .
getElementsByClassName(classNames)
- collection = element .
- Returns a
HTMLCollection
of the elements in the object on which the method was invoked (a document or an element) that have all the classes given by classNames. The classNames argument is interpreted as a space-separated list of classes.
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IE6+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+
The doctype
attribute’s getter must return the child of the document that is a doctype, and null otherwise.
In all current engines.
Opera7+Edge79+
Edge (Legacy)12+IE5+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
The documentElement
attribute’s getter must return
the document element.
In all current engines.
Opera5.1+Edge79+
Edge (Legacy)12+IE5+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
The getElementsByTagName(qualifiedName)
method, when invoked, must return the list of elements with qualified name qualifiedName for this.
Thus, in an HTML document, document
will match <FOO>
elements that are not in the HTML namespace, and <foo>
elements that are in
the HTML namespace, but not <FOO>
elements
that are in the HTML namespace.
Document/getElementsByTagNameNS
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+
The getElementsByTagNameNS(namespace, localName)
method, when invoked, must return the list of elements with namespace namespace and local name localName for this.
Document/getElementsByClassName
In all current engines.
Opera9.5+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari2+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
The getElementsByClassName(classNames)
method, when invoked, must return the list of elements with class names classNames for this.
< div id = "example" >
< p id = "p1" class = "aaa bbb" />
< p id = "p2" class = "aaa ccc" />
< p id = "p3" class = "bbb ccc" />
</ div >
A call to document
would return a HTMLCollection
with the two paragraphs p1
and p2
in it.
A call to getElementsByClassName
would only return one node, however, namely p3
. A call to document
would return the same thing.
A call to getElementsByClassName
would return no nodes; none of the elements above are in the aaa,bbb
class.
element = document . createElement(localName [, options])
-
Returns an element with localName as local name (if document is an HTML document, localName gets lowercased). The element’s namespace is the HTML namespace when document is an HTML document or document’s content type is "
application/xhtml+xml
", and null otherwise.If localName does not match the
Name
production an "InvalidCharacterError
"DOMException
will be thrown.When supplied, options’s
is
can be used to create a customized built-in element. element = document . createElementNS(namespace, qualifiedName [, options])
-
Returns an element with namespace namespace. Its namespace prefix will be everything before "
:
" (U+003E) in qualifiedName or null. Its local name will be everything after ":
" (U+003E) in qualifiedName or qualifiedName.If localName does not match the
Name
production an "InvalidCharacterError
"DOMException
will be thrown.If one of the following conditions is true a "
NamespaceError
"DOMException
will be thrown:- localName does not match the
QName
production. - Namespace prefix is not null and namespace is the empty string.
- Namespace prefix is "
xml
" and namespace is not the XML namespace. - qualifiedName or namespace prefix is "
xmlns
" and namespace is not the XMLNS namespace. - namespace is the XMLNS namespace and
neither qualifiedName nor namespace prefix is "
xmlns
".
When supplied, options’s
is
can be used to create a customized built-in element. - localName does not match the
documentFragment = document .
createDocumentFragment()
- Returns a
DocumentFragment
node. text = document .
createTextNode(data)
- Returns a
Text
node whose data is data. text = document .
createCDATASection(data)
- Returns a
CDATASection
node whose data is data. comment = document .
createComment(data)
- Returns a
Comment
node whose data is data. processingInstruction = document .
createProcessingInstruction(target, data)
- Returns a
ProcessingInstruction
node whose target is target and data is data. If target does not match theName
production an "InvalidCharacterError
"DOMException
will be thrown. If data contains "?>
" an "InvalidCharacterError
"DOMException
will be thrown.
The element interface for any name and namespace is Element
, unless
stated otherwise.
The HTML Standard will e.g. define that for html
and the HTML namespace, the HTMLHtmlElement
interface is used. [HTML]
In all current engines.
Opera6+Edge79+
Edge (Legacy)12+IE5+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
The createElement(localName, options)
method, when
invoked, must run these steps:
-
If localName does not match the
Name
production, then throw an "InvalidCharacterError
"DOMException
. -
If this is an HTML document, then set localName to localName in ASCII lowercase.
-
Let is be null.
-
If options is a dictionary and options’s
is
is present, then set is to it. -
Let namespace be the HTML namespace, if this is an HTML document or this’s content type is "
application/xhtml+xml
", and null otherwise. -
Return the result of creating an element given this, localName, namespace, null, is, and with the synchronous custom elements flag set.
The internal createElementNS
steps, given document, namespace, qualifiedName, and options, are as follows:
-
Let namespace, prefix, and localName be the result of passing namespace and qualifiedName to validate and extract.
-
Let is be null.
-
If options is a dictionary and options’s
is
is present, then set is to it. -
Return the result of creating an element given document, localName, namespace, prefix, is, and with the synchronous custom elements flag set.
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+
The createElementNS(namespace, qualifiedName, options)
method, when invoked, must return the result of running the internal createElementNS
steps, given this, namespace, qualifiedName, and options.
createElement()
and createElementNS()
's options parameter is allowed to be a string for web compatibility.
Document/createDocumentFragment
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IE6+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+
The createDocumentFragment()
method, when invoked,
must return a new DocumentFragment
node with its node document set to this.
In all current engines.
Opera7+Edge79+
Edge (Legacy)12+IE5+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
The createTextNode(data)
method, when
invoked, must return a new Text
node with its data set to data and node document set to this.
No check is performed that data consists of
characters that match the Char
production.
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+
The createCDATASection(data)
method, when
invoked, must run these steps:
-
If this is an HTML document, then throw a "
NotSupportedError
"DOMException
. -
If data contains the string "
]]>
", then throw an "InvalidCharacterError
"DOMException
. -
Return a new
CDATASection
node with its data set to data and node document set to this.
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IE6+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+
The createComment(data)
method, when invoked,
must return a new Comment
node with its data set to data and node document set to this.
No check is performed that data consists of
characters that match the Char
production
or that it contains two adjacent hyphens or ends with a hyphen.
Document/createProcessingInstruction
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+
The createProcessingInstruction(target, data)
method, when invoked, must run these steps:
- If target does not match the
Name
production, then throw an "InvalidCharacterError
"DOMException
. - If data contains the string
"
?>
", then throw an "InvalidCharacterError
"DOMException
. - Return a new
ProcessingInstruction
node, with target set to target, data set to data, and node document set to this.
No check is performed that target contains
"xml
" or ":
", or that data contains characters that match the Char
production.
- clone = document . importNode(node [, deep = false])
-
Returns a copy of node. If deep is true, the copy also includes the node’s descendants.
If node is a document or a shadow root, throws a "
NotSupportedError
"DOMException
. - node = document .
adoptNode(node)
-
Moves node from another document and returns it.
If node is a document, throws a "
NotSupportedError
"DOMException
or, if node is a shadow root, throws a "HierarchyRequestError
"DOMException
.
In all current engines.
Opera9+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
The importNode(node, deep)
method,
when invoked, must run these steps:
-
If node is a document or shadow root, then throw a "
NotSupportedError
"DOMException
. -
Return a clone of node, with this and the clone children flag set if deep is true.
Specifications may define adopting steps for all or some nodes. The algorithm is passed node and oldDocument, as indicated in the adopt algorithm.
To adopt a node into a document, run these steps:
-
Let oldDocument be node’s node document.
-
If document is not oldDocument, then:
-
For each inclusiveDescendant in node’s shadow-including inclusive descendants:
-
Set inclusiveDescendant’s node document to document.
-
If inclusiveDescendant is an element, then set the node document of each attribute in inclusiveDescendant’s attribute list to document.
-
-
For each inclusiveDescendant in node’s shadow-including inclusive descendants that is custom, enqueue a custom element callback reaction with inclusiveDescendant, callback name "
adoptedCallback
", and an argument list containing oldDocument and document. -
For each inclusiveDescendant in node’s shadow-including inclusive descendants, in shadow-including tree order, run the adopting steps with inclusiveDescendant and oldDocument.
-
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+
The adoptNode(node)
method, when invoked,
must run these steps:
-
If node is a document, then throw a "
NotSupportedError
"DOMException
. -
If node is a shadow root, then throw a "
HierarchyRequestError
"DOMException
. -
If node is a
DocumentFragment
node whose host is non-null, then return. -
Return node.
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IE6+
Firefox for Android44+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+
The createAttribute(localName)
method, when
invoked, must run these steps:
-
If localName does not match the
Name
production in XML, then throw an "InvalidCharacterError
"DOMException
. - If this is an HTML document, then set localName to localName in ASCII lowercase.
- Return a new attribute whose local name is localName and node document is this.
The createAttributeNS(namespace, qualifiedName)
method, when invoked, must run these steps:
-
Let namespace, prefix, and localName be the result of passing namespace and qualifiedName to validate and extract.
-
Return a new attribute whose namespace is namespace, namespace prefix is prefix, local name is localName, and node document is this.
In all current engines.
Opera7+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
The createEvent(interface)
method, when
invoked, must run these steps:
-
Let constructor be null.
-
If interface is an ASCII case-insensitive match for any of the strings in the first column in the following table, then set constructor to the interface in the second column on the same row as the matching string:
String Interface Notes " beforeunloadevent
"BeforeUnloadEvent
[HTML] " compositionevent
"CompositionEvent
[UIEVENTS] " customevent
"CustomEvent
" devicemotionevent
"DeviceMotionEvent
[DEVICE-ORIENTATION] " deviceorientationevent
"DeviceOrientationEvent
" dragevent
"DragEvent
[HTML] " event
"Event
" events
"" focusevent
"FocusEvent
[UIEVENTS] " hashchangeevent
"HashChangeEvent
[HTML] " htmlevents
"Event
" keyboardevent
"KeyboardEvent
[UIEVENTS] " messageevent
"MessageEvent
[HTML] " mouseevent
"MouseEvent
[UIEVENTS] " mouseevents
"" storageevent
"StorageEvent
[HTML] " svgevents
"Event
" textevent
"CompositionEvent
[UIEVENTS] " touchevent
"TouchEvent
[TOUCH-EVENTS] " uievent
"UIEvent
[UIEVENTS] " uievents
" -
If constructor is null, then throw a "
NotSupportedError
"DOMException
. -
If the interface indicated by constructor is not exposed on the relevant global object of this, then throw a "
NotSupportedError
"DOMException
.Typically user agents disable support for touch events in some configurations, in which case this clause would be triggered for the interface
TouchEvent
. -
Let event be the result of creating an event given constructor.
-
Initialize event’s
type
attribute to the empty string. -
Initialize event’s
timeStamp
attribute to aDOMHighResTimeStamp
representing the high resolution time from the time origin to now. -
Initialize event’s
isTrusted
attribute to false. -
Unset event’s initialized flag.
-
Return event.
Event constructors ought to be used instead.
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+
The createRange()
method, when invoked, must return a
new live range with (this, 0) as its start an end.
The Range()
constructor can be used instead.
In all current engines.
Opera9+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari1+Chrome for AndroidYesAndroid WebViewYesSamsung InternetYesOpera MobileYes
The createNodeIterator(root, whatToShow, filter)
method, when invoked, must run these steps:
-
Let iterator be a new
NodeIterator
object. -
Set iterator’s pointer before reference to true.
-
Set iterator’s whatToShow to whatToShow.
-
Set iterator’s filter to filter.
-
Return iterator.
In all current engines.
Opera9+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari3+Chrome for AndroidYesAndroid WebViewYesSamsung InternetYesOpera Mobile10.1+
The createTreeWalker(root, whatToShow, filter)
method, when invoked, must run these steps:
-
Let walker be a new
TreeWalker
object. -
Set walker’s whatToShow to whatToShow.
-
Set walker’s filter to filter.
- Return walker.
4.5.1. Interface DOMImplementation
User agents must create a DOMImplementation
object whenever
a document is created and associate it
with that document.
In all current engines.
OperaYesEdgeYes
Edge (Legacy)12+IE6+
Firefox for Android4+iOS Safari3+Chrome for AndroidYesAndroid WebViewYesSamsung InternetYesOpera MobileYes
[Exposed =Window ]interface { [
DOMImplementation NewObject ]DocumentType createDocumentType (DOMString ,
qualifiedName DOMString ,
publicId DOMString ); [
systemId NewObject ]XMLDocument createDocument (DOMString ?, [
namespace LegacyNullToEmptyString ]DOMString ,
qualifiedName optional DocumentType ?=
doctype null ); [NewObject ]Document createHTMLDocument (optional DOMString );
title boolean hasFeature (); // useless; always returns true };
doctype = document .
implementation
.createDocumentType(qualifiedName, publicId, systemId)
- Returns a doctype, with the given qualifiedName, publicId, and systemId. If qualifiedName does not
match the
Name
production, an "InvalidCharacterError
"DOMException
is thrown, and if it does not match theQName
production, a "NamespaceError
"DOMException
is thrown. doc = document .
implementation
. createDocument(namespace, qualifiedName [, doctype = null])-
Returns an
XMLDocument
, with a document element whose local name is qualifiedName and whose namespace is namespace (unless qualifiedName is the empty string), and with doctype, if it is given, as its doctype.This method throws the same exceptions as the
createElementNS()
method, when invoked with namespace and qualifiedName. doc = document .
implementation
. createHTMLDocument([title])- Returns a document, with a basic tree already constructed including a
title
element, unless the title argument is omitted.
DOMImplementation/createDocumentType
In all current engines.
OperaYesEdgeYes
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari3+Chrome for AndroidYesAndroid WebViewYesSamsung InternetYesOpera MobileYes
The createDocumentType(qualifiedName, publicId, systemId)
method, when invoked, must run these steps:
-
Validate qualifiedName.
-
Return a new doctype, with qualifiedName as its name, publicId as its public ID, and systemId as its system ID, and with its node document set to the associated document of this.
No check is performed that publicId code points match the PubidChar
production or that systemId does not contain both a
'"
' and a "'
".
DOMImplementation/createDocument
In all current engines.
OperaYesEdgeYes
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari3+Chrome for AndroidYesAndroid WebViewYesSamsung InternetYesOpera MobileYes
The createDocument(namespace, qualifiedName, doctype)
method, when invoked, must run these steps:
-
Let document be a new
XMLDocument
. -
Let element be null.
-
If qualifiedName is not the empty string, then set element to the result of running the internal
createElementNS
steps, given document, namespace, qualifiedName, and an empty dictionary. -
If doctype is non-null, append doctype to document.
-
If element is non-null, append element to document.
-
document’s content type is determined by namespace:
- HTML namespace
application/xhtml+xml
- SVG namespace
image/svg+xml
- Any other namespace
application/xml
-
Return document.
DOMImplementation/createHTMLDocument
In all current engines.
OperaYesEdgeYes
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari3+Chrome for AndroidYesAndroid WebViewYesSamsung InternetYesOpera MobileYes
The createHTMLDocument(title)
method, when invoked, must run these steps:
-
Let doc be a new document that is an HTML document.
-
Set doc’s content type to "
text/html
". -
Append a new doctype, with "
html
" as its name and with its node document set to doc, to doc. -
Append the result of creating an element given doc,
html
, and the HTML namespace, to doc. -
Append the result of creating an element given doc,
head
, and the HTML namespace, to thehtml
element created earlier. -
If title is given:
-
Append the result of creating an element given doc,
title
, and the HTML namespace, to thehead
element created earlier. -
Append a new
Text
node, with its data set to title (which could be the empty string) and its node document set to doc, to thetitle
element created earlier.
-
-
Append the result of creating an element given doc,
body
, and the HTML namespace, to thehtml
element created earlier. -
Return doc.
The hasFeature()
method, when
invoked, must return true.
hasFeature()
originally would report whether the user agent
claimed to support a given DOM feature, but experience proved it was not nearly as
reliable or granular as simply checking whether the desired objects, attributes, or
methods existed. As such, it is no longer to be used, but continues to exist (and simply
returns true) so that old pages don’t stop working.
4.6. Interface DocumentType
In all current engines.
OperaYesEdgeYes
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari3+Chrome for AndroidYesAndroid WebViewYesSamsung InternetYesOpera MobileYes
[Exposed =Window ]interface :
DocumentType Node {readonly attribute DOMString name ;readonly attribute DOMString publicId ;readonly attribute DOMString systemId ; };
DocumentType
nodes are simply known as doctypes.
Doctypes have an associated name, public ID, and system ID.
When a doctype is created, its name is always given. Unless explicitly given when a doctype is created, its public ID and system ID are the empty string.
The name
attribute’s getter must return this’s name.
The publicId
attribute’s getter must return this’s public ID.
The systemId
attribute’s getter must return this’s system ID.
4.7. Interface DocumentFragment
In all current engines.
Opera8+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
[Exposed =Window ]interface :
DocumentFragment Node {constructor (); };
A DocumentFragment
node has an associated host (null or an element in a different node tree). It is null unless otherwise stated.
An object A is a host-including inclusive ancestor of an object B, if either A is an inclusive ancestor of B, or if B’s root has a non-null host and A is a host-including inclusive ancestor of B’s root’s host.
The DocumentFragment
node’s host concept is useful for HTML’s template
element and for shadow roots, and impacts the pre-insert and replace algorithms.
tree = new
DocumentFragment()
- Returns a new
DocumentFragment
node.
DocumentFragment/DocumentFragment
In all current engines.
Opera15+Edge79+
Edge (Legacy)18IENone
Firefox for Android24+iOS Safari8+Chrome for AndroidYesAndroid WebViewYesSamsung InternetYesOpera MobileYes
The DocumentFragment()
constructor, when
invoked, must return a new DocumentFragment
node whose node document is current global object’s associated Document
.
4.8. Interface ShadowRoot
In all current engines.
Opera40+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android63+iOS Safari10.3+Chrome for Android57+Android WebView57+Samsung Internet6.0+Opera Mobile41+
[Exposed =Window ]interface :
ShadowRoot DocumentFragment {readonly attribute ShadowRootMode mode ;readonly attribute Element host ;attribute EventHandler onslotchange ; };enum {
ShadowRootMode ,
"open" };
"closed"
ShadowRoot
nodes are simply known as shadow roots.
Shadow roots have an associated mode ("open
"
or "closed
").
Shadow roots have an associated delegates focus. It is initially set to false.
Shadow roots have an associated available to element internals. It is initially set to false.
Shadow roots’s associated host is never null.
A shadow root’s get the parent algorithm, given an event, returns null if event’s composed flag is unset and shadow root is the root of event’s path’s first struct’s invocation target, and shadow root’s host otherwise.
In all current engines.
Opera40+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android63+iOS Safari10.3+Chrome for Android57+Android WebView57+Samsung Internet6.0+Opera Mobile41+
The mode
attribute’s getter must return this’s mode.
In all current engines.
Opera40+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android63+iOS Safari10.3+Chrome for Android57+Android WebView57+Samsung Internet6.0+Opera Mobile41+
The host
attribute’s getter must return this’s host.
The onslotchange
attribute is an event handler IDL attribute for the onslotchange
event handler, whose event handler event type is slotchange
.
In shadow-including tree order is shadow-including preorder, depth-first traversal of a node tree. Shadow-including preorder, depth-first traversal of a node tree tree is preorder, depth-first traversal of tree, with for each shadow host encountered in tree, shadow-including preorder, depth-first traversal of that element’s shadow root’s node tree just after it is encountered.
The shadow-including root of an object is its root’s host’s shadow-including root, if the object’s root is a shadow root, and its root otherwise.
An object A is a shadow-including descendant of an object B, if A is a descendant of B, or A’s root is a shadow root and A’s root’s host is a shadow-including inclusive descendant of B.
A shadow-including inclusive descendant is an object or one of its shadow-including descendants.
An object A is a shadow-including ancestor of an object B, if and only if B is a shadow-including descendant of A.
A shadow-including inclusive ancestor is an object or one of its shadow-including ancestors.
A node A is closed-shadow-hidden from a node B if all of the following conditions are true:
-
A’s root is a shadow root.
-
A’s root is not a shadow-including inclusive ancestor of B.
-
A’s root is a shadow root whose mode is "
closed
" or A’s root’s host is from B.
To retarget an object A against an object B, repeat these steps until they return an object:
-
If one of the following is true
- A is not a node
- A’s root is not a shadow root
- B is a node and A’s root is a shadow-including inclusive ancestor of B
then return A.
The retargeting algorithm is used by event dispatch as well as other specifications, such as Fullscreen. [FULLSCREEN]
4.9. Interface Element
In all current engines.
Opera8+Edge79+
Edge (Legacy)12+IE4+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
[Exposed =Window ]interface :
Element Node {readonly attribute DOMString ?namespaceURI ;readonly attribute DOMString ?prefix ;readonly attribute DOMString localName ;readonly attribute DOMString tagName ; [CEReactions ]attribute DOMString id ; [CEReactions ]attribute DOMString className ; [SameObject ,PutForwards =value ]readonly attribute DOMTokenList classList ; [CEReactions ,Unscopable ]attribute DOMString slot ;boolean hasAttributes (); [SameObject ]readonly attribute NamedNodeMap attributes ;sequence <DOMString >getAttributeNames ();DOMString ?getAttribute (DOMString );
qualifiedName DOMString ?getAttributeNS (DOMString ?,
namespace DOMString ); [
localName CEReactions ]undefined setAttribute (DOMString ,
qualifiedName DOMString ); [
value CEReactions ]undefined setAttributeNS (DOMString ?,
namespace DOMString ,
qualifiedName DOMString ); [
value CEReactions ]undefined removeAttribute (DOMString ); [
qualifiedName CEReactions ]undefined removeAttributeNS (DOMString ?,
namespace DOMString ); [
localName CEReactions ]boolean toggleAttribute (DOMString ,
qualifiedName optional boolean );
force boolean hasAttribute (DOMString );
qualifiedName boolean hasAttributeNS (DOMString ?,
namespace DOMString );
localName Attr ?getAttributeNode (DOMString );
qualifiedName Attr ?getAttributeNodeNS (DOMString ?,
namespace DOMString ); [
localName CEReactions ]Attr ?setAttributeNode (Attr ); [
attr CEReactions ]Attr ?setAttributeNodeNS (Attr ); [
attr CEReactions ]Attr removeAttributeNode (Attr );
attr ShadowRoot attachShadow (ShadowRootInit );
init readonly attribute ShadowRoot ?shadowRoot ;Element ?closest (DOMString );
selectors boolean matches (DOMString );
selectors boolean webkitMatchesSelector (DOMString ); // legacy alias of .matches
selectors HTMLCollection getElementsByTagName (DOMString );
qualifiedName HTMLCollection getElementsByTagNameNS (DOMString ?,
namespace DOMString );
localName HTMLCollection getElementsByClassName (DOMString ); [
classNames CEReactions ]Element ?insertAdjacentElement (DOMString ,
where Element ); // legacy
element undefined insertAdjacentText (DOMString ,
where DOMString ); // legacy };
data dictionary {
ShadowRootInit required ShadowRootMode ;
mode boolean =
delegatesFocus false ; };
Element
nodes are simply known as elements.
Elements have an associated namespace, namespace prefix, local name, custom element state, custom element definition, is
value. When an element is created, all of these values are
initialized.
An element’s custom element state is one of
"undefined
", "failed
", "uncustomized
",
"precustomized
", or "custom
". An element whose custom element state is "uncustomized
" or "custom
" is
said to be defined. An element whose custom element state is "custom
" is said to be custom.
Whether or not an element is defined is used to determine the
behavior of the :defined pseudo-class. Whether or not an element is custom is
used to determine the behavior of the mutation algorithms. The
"failed
" and "precustomized
" states are used to ensure that if a custom element constructor fails to execute correctly the first time, it is not executed
again by an upgrade.
The following code illustrates elements in each of these four states:
<!DOCTYPE html>
< script >
window. customElements. define( "sw-rey" , class extends HTMLElement {})
window. customElements. define( "sw-finn" , class extends HTMLElement {}, { extends : "p" })
window. customElements. define( "sw-kylo" , class extends HTMLElement {
constructor() {
// super() intentionally omitted for this example
}
})
</ script >
<!-- "undefined" (not defined, not custom) -->
< sw-han ></ sw-han >
< p is = "sw-luke" ></ p >
< p is = "asdf" ></ p >
<!-- "failed" (not defined, not custom) -->
< sw-kylo ></ sw-kylo >
<!-- "uncustomized" (defined, not custom) -->
< p ></ p >
< asdf ></ asdf >
<!-- "custom" (defined, custom) -->
< sw-rey ></ sw-rey >
< p is = "sw-finn" ></ p >
Elements also have an associated shadow root (null or a shadow root). It is null unless otherwise stated. An element is a shadow host if its shadow root is non-null.
An element’s qualified name is its local name if its namespace prefix is null, and its namespace prefix, followed by ":
", followed by its local name, otherwise.
An element’s HTML-uppercased qualified name is the return value of these steps:
-
Let qualifiedName be this’s qualified name.
-
If this is in the HTML namespace and its node document is an HTML document, then set qualifiedName to qualifiedName in ASCII uppercase.
- Return qualifiedName.
User agents could optimize qualified name and HTML-uppercased qualified name by storing them in internal slots.
To create an element, given a document, localName, namespace, and optional prefix, is, and synchronous custom elements flag, run these steps:
-
If prefix was not given, let prefix be null.
-
If is was not given, let is be null.
-
Let result be null.
-
Let definition be the result of looking up a custom element definition given document, namespace, localName, and is.
-
If definition is non-null, and definition’s name is not equal to its local name (i.e., definition represents a customized built-in element), then:
-
Let interface be the element interface for localName and the HTML namespace.
-
Set result to a new element that implements interface, with no attributes, namespace set to the HTML namespace, namespace prefix set to prefix, local name set to localName, custom element state set to "
undefined
", custom element definition set to null,is
value set to is, and node document set to document. -
If the synchronous custom elements flag is set, then run this step while catching any exceptions:
-
Upgrade element using definition.
If this step threw an exception, then:
-
Set result’s custom element state to "
failed
".
-
-
Otherwise, enqueue a custom element upgrade reaction given result and definition.
-
-
Otherwise, if definition is non-null, then:
-
If the synchronous custom elements flag is set, then run these steps while catching any exceptions:
-
Let C be definition’s constructor.
-
Set result to the result of constructing C, with no arguments.
-
Assert: result’s custom element state and custom element definition are initialized.
-
Assert: result’s namespace is the HTML namespace.
IDL enforces that result is an
HTMLElement
object, which all use the HTML namespace. -
If result’s attribute list is not empty, then throw a "
NotSupportedError
"DOMException
. -
If result has children, then throw a "
NotSupportedError
"DOMException
. -
If result’s parent is not null, then throw a "
NotSupportedError
"DOMException
. -
If result’s node document is not document, then throw a "
NotSupportedError
"DOMException
. -
If result’s local name is not equal to localName, then throw a "
NotSupportedError
"DOMException
. -
Set result’s namespace prefix to prefix.
-
Set result’s
is
value to null.
If any of these steps threw an exception, then:
-
Set result to a new element that implements the
HTMLUnknownElement
interface, with no attributes, namespace set to the HTML namespace, namespace prefix set to prefix, local name set to localName, custom element state set to "failed
", custom element definition set to null,is
value set to null, and node document set to document.
-
-
Otherwise:
-
Set result to a new element that implements the
HTMLElement
interface, with no attributes, namespace set to the HTML namespace, namespace prefix set to prefix, local name set to localName, custom element state set to "undefined
", custom element definition set to null,is
value set to null, and node document set to document. -
Enqueue a custom element upgrade reaction given result and definition.
-
-
-
Otherwise:
-
Let interface be the element interface for localName and namespace.
-
Set result to a new element that implements interface, with no attributes, namespace set to namespace, namespace prefix set to prefix, local name set to localName, custom element state set to "
uncustomized
", custom element definition set to null,is
value set to is, and node document set to document. -
If namespace is the HTML namespace, and either localName is a valid custom element name or is is non-null, then set result’s custom element state to "
undefined
".
-
-
Return result.
Elements also have an attribute list, which is a list exposed through a NamedNodeMap
. Unless explicitly given when an element is created, its attribute list is empty.
An element has an attribute A if its attribute list contains A.
This and other specifications may define attribute change steps for elements. The algorithm is passed element, localName, oldValue, value, and namespace.
To handle attribute changes for an attribute attribute with element, oldValue, and newValue, run these steps:
-
Queue a mutation record of "
attributes
" for element with attribute’s local name, attribute’s namespace, oldValue, « », « », null, and null. -
If element is custom, then enqueue a custom element callback reaction with element, callback name "
attributeChangedCallback
", and an argument list containing attribute’s local name, oldValue, newValue, and attribute’s namespace. -
Run the attribute change steps with element, attribute’s local name, oldValue, newValue, and attribute’s namespace.
To change an attribute attribute to value, run these steps:
-
Handle attribute changes for attribute with attribute’s element, attribute’s value, and value.
-
Set attribute’s value to value.
To append an attribute attribute to an element element, run these steps:
-
Handle attribute changes for attribute with element, null, and attribute’s value.
-
Append attribute to element’s attribute list.
-
Set attribute’s element to element.
To remove an attribute attribute, run these steps:
-
Handle attribute changes for attribute with attribute’s element, attribute’s value, and null.
- Remove attribute from attribute’s element’s attribute list.
-
Set attribute’s element to null.
To replace an attribute oldAttr with an attribute newAttr, run these steps:
-
Handle attribute changes for oldAttr with oldAttr’s element, oldAttr’s value, and newAttr’s value.
-
Replace oldAttr by newAttr in oldAttr’s element’s attribute list.
-
Set oldAttr’s element to null.
To get an attribute by name given a qualifiedName and element element, run these steps:
-
If element is in the HTML namespace and its node document is an HTML document, then set qualifiedName to qualifiedName in ASCII lowercase.
-
Return the first attribute in element’s attribute list whose qualified name is qualifiedName, and null otherwise.
To get an attribute by namespace and local name given a namespace, localName, and element element, run these steps:
- If namespace is the empty string, set it to null.
- Return the attribute in element’s attribute list whose namespace is namespace and local name is localName, if any, and null otherwise.
To get an attribute value given an element element, localName, and optionally a namespace (null unless stated otherwise), run these steps:
-
Let attr be the result of getting an attribute given namespace, localName, and element.
-
If attr is null, then return the empty string.
-
Return attr’s value.
To set an attribute given an attr and element, run these steps:
-
If attr’s element is neither null nor element, throw an "
InUseAttributeError
"DOMException
. -
Let oldAttr be the result of getting an attribute given attr’s namespace, attr’s local name, and element.
-
If oldAttr is attr, return attr.
-
If oldAttr is non-null, then replace oldAttr with attr.
-
Otherwise, append attr to element.
-
Return oldAttr.
To set an attribute value for an element element, using a localName and value, and an optional prefix, and namespace, run these steps:
- If prefix is not given, set it to null.
- If namespace is not given, set it to null.
- Let attribute be the result of getting an attribute given namespace, localName, and element.
- If attribute is null, create an attribute whose namespace is namespace, namespace prefix is prefix, local name is localName, value is value, and node document is element’s node document, then append this attribute to element, and then return.
-
Change attribute to value.
To remove an attribute by name given a qualifiedName and element element, run these steps:
-
Let attr be the result of getting an attribute given qualifiedName and element.
-
If attr is non-null, then remove attr.
-
Return attr.
To remove an attribute by namespace and local name given a namespace, localName, and element element, run these steps:
-
Let attr be the result of getting an attribute given namespace, localName, and element.
-
If attr is non-null, then remove attr.
-
Return attr.
An element can have an associated unique identifier (ID)
Historically elements could have multiple identifiers e.g., by using
the HTML id
attribute and a DTD. This specification makes ID a concept of the DOM and allows for only one per element, given by an id
attribute.
Use these attribute change steps to update an element’s ID:
-
If localName is
id
, namespace is null, and value is null or the empty string, then unset element’s ID. -
Otherwise, if localName is
id
, namespace is null, then set element’s ID to value.
While this specification defines requirements for class
, id
, and slot
attributes on any element, it makes no
claims as to whether using them is conforming or not.
A node’s parent of type Element
is known as a parent element. If the node has a parent of a different type, its parent element is null.
- namespace = element .
namespaceURI
- Returns the namespace.
- prefix = element .
prefix
- Returns the namespace prefix.
- localName = element .
localName
- Returns the local name.
- qualifiedName = element .
tagName
- Returns the HTML-uppercased qualified name.
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android48+iOS Safari10+Chrome for Android31+Android WebView4.4.3+Samsung Internet2.0+Opera Mobile12.1+
The namespaceURI
attribute’s getter must return this’s namespace.
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)13+IE9+
Firefox for Android48+iOS Safari10+Chrome for Android31+Android WebView4.4.3+Samsung Internet2.0+Opera Mobile12.1+
The prefix
attribute’s getter must return this’s namespace prefix.
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IE9+
Firefox for Android48+iOS Safari10+Chrome for Android31+Android WebView4.4.3+Samsung Internet2.0+Opera Mobile12.1+
The localName
attribute’s getter must return this’s local name.
In all current engines.
Opera8+Edge79+
Edge (Legacy)12+IE5+
Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+
The tagName
attribute’s getter must return this’s HTML-uppercased qualified name.
element . id [ = value ]
-
Returns the value of element’s
id
content attribute. Can be set to change it. element . className [ = value ]
-
Returns the value of element’s
class
content attribute. Can be set to change it. element . classList
-
Allows for manipulation of element’s
class
content attribute as a set of whitespace-separated tokens through aDOMTokenList
object. element . slot [ = value ]
-
Returns the value of element’s
slot
content attribute. Can be set to change it.
IDL attributes that are defined to reflect a content attribute of a given name, must have a getter and setter that follow these steps:
- getter
-
Return the result of running get an attribute value given this and name.
- setter
-
Set an attribute value for this using name and the given value.
In all current engines.
Opera12.1+Edge79+
Edge (Legacy)12+IE5+
Firefox for Android4+iOS Safari1+Chrome for Android25+Android WebView37+Samsung Internet1.5+Opera Mobile12.1+
The id
attribute must reflect the
"id
" content attribute.
In all current engines.
Opera8+Edge79+
Edge (Legacy)12+IE5+
Firefox for Android4+iOS Safari1+Chrome for Android25+Android WebView37+Samsung Internet1.5+Opera Mobile10.1+
The className
attribute must reflect the "class
" content attribute.
In all current engines.
Opera11.5+Edge79+
Edge (Legacy)16+IENone
Firefox for Android4+iOS Safari7+Chrome for Android25+Android WebView4.4+Samsung Internet1.5+Opera Mobile11.5+
The classList
attribute’s getter must return a DOMTokenList
object whose associated element is this and whose associated attribute’s local name is class
. The token set of this
particular DOMTokenList
object are also known as the element’s classes.
In all current engines.
Opera40+Edge79+
Edge (Legacy)NoneIENone
Firefox for Android63+iOS Safari10+Chrome for Android53+Android WebView53+Samsung Internet6.0+Opera Mobile41+
In all current engines.
Opera40+Edge79+
Edge (Legacy)NoneIE?
Firefox for Android63+iOS Safari10+Chrome for Android53+Android WebView53+Samsung Internet6.0+Opera Mobile41+
The slot
attribute must reflect the
"slot
" content attribute.
id
, class
, and slot
are effectively
superglobal attributes as they can appear on any element, regardless of that element’s
namespace.
element . hasAttributes()
-
Returns true if element has attributes, and false otherwise.
element . getAttributeNames()
-
Returns the qualified names of all element’s attributes. Can contain duplicates.
element . getAttribute(qualifiedName)
-
Returns element’s first attribute whose qualified name is qualifiedName, and null if there is no such attribute otherwise.
element . getAttributeNS(namespace, localName)
-
Returns element’s attribute whose namespace is namespace and local name is localName, and null if there is no such attribute otherwise.
element . setAttribute(qualifiedName, value)
-
Sets the value of element’s first attribute whose qualified name is qualifiedName to value.
element . setAttributeNS(namespace, localName, value)
-
Sets the value of element’s attribute whose namespace is namespace and local name is localName to value.
element . removeAttribute(qualifiedNa