Skip to content

DOM standard

Bryan-Guner-Backup edited this page May 28, 2022 · 1 revision

DOM Standard

Excerpt

This specification depends on the Infra Standard. [INFRA]


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]

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:

  1. Let inputTokens be the result of splitting input on ASCII whitespace.

  2. Let tokens be a new ordered set.

  3. For each token in inputTokens, append token to tokens.

  4. 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:

  1. Let s be the result of parse a selector selectors. [SELECTORS4]

  2. If s is failure, then throw a "[SyntaxError](https://webidl.spec.whatwg.org/#syntaxerror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  3. 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](https://webidl.spec.whatwg.org/#invalidcharactererror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException) if qualifiedName does not match the [QName](https://www.w3.org/TR/xml-names/#NT-QName) production.

To validate and extract a namespace and qualifiedName, run these steps:

  1. If namespace is the empty string, then set it to null.

  2. Validate qualifiedName.

  3. Let prefix be null.

  4. Let localName be qualifiedName.

  5. If qualifiedName contains a U+003A (:), then strictly split the string on it and set prefix to the part before and localName to the part after.

  6. If prefix is non-null and namespace is null, then throw a "[NamespaceError](https://webidl.spec.whatwg.org/#namespaceerror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  7. If prefix is "xml" and namespace is not the XML namespace, then throw a "[NamespaceError](https://webidl.spec.whatwg.org/#namespaceerror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  8. If either qualifiedName or prefix is "xmlns" and namespace is not the XMLNS namespace, then throw a "[NamespaceError](https://webidl.spec.whatwg.org/#namespaceerror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  9. If namespace is the XMLNS namespace and neither qualifiedName nor prefix is "xmlns", then throw a "[NamespaceError](https://webidl.spec.whatwg.org/#namespaceerror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  10. 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](https://dom.spec.whatwg.org/#eventtarget) interface and can therefore add event listeners to observe events by calling [addEventListener()](https://dom.spec.whatwg.org/#dom-eventtarget-addeventlistener):

obj.addEventListener("load", imgFetched)

function imgFetched(ev) { // great success … }

Event listeners can be removed by utilizing the [removeEventListener()](https://dom.spec.whatwg.org/#dom-eventtarget-removeeventlistener) method, passing the same arguments.

Alternatively, event listeners can be removed by passing an [AbortSignal](https://dom.spec.whatwg.org/#abortsignal) to [addEventListener()](https://dom.spec.whatwg.org/#dom-eventtarget-addeventlistener) and calling [abort()](https://dom.spec.whatwg.org/#dom-abortcontroller-abort) on the controller owning the signal.

Events are objects too and implement the [Event](https://dom.spec.whatwg.org/#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](https://dom.spec.whatwg.org/#dom-event-type) attribute value ("load" in the above example). The event’s [target](https://dom.spec.whatwg.org/#dom-event-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](https://dom.spec.whatwg.org/#dom-event-type) attribute value is "submit" is dispatched. If this event’s [preventDefault()](https://dom.spec.whatwg.org/#dom-event-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()](https://dom.spec.whatwg.org/#dom-eventtarget-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](https://dom.spec.whatwg.org/#dom-event-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](https://dom.spec.whatwg.org/#dom-event-target) attribute value will be the span element. The first time [currentTarget](https://dom.spec.whatwg.org/#dom-event-currenttarget) attribute’s value will be the document, the second time the body element. [eventPhase](https://dom.spec.whatwg.org/#dom-event-eventphase) attribute’s value switches from [CAPTURING_PHASE](https://dom.spec.whatwg.org/#dom-event-capturing_phase) to [BUBBLING_PHASE](https://dom.spec.whatwg.org/#dom-event-bubbling_phase). If an event listener was registered for the span element, [eventPhase](https://dom.spec.whatwg.org/#dom-event-eventphase) attribute’s value would have been [AT_TARGET](https://dom.spec.whatwg.org/#dom-event-at_target).

2.2. Interface [Event](https://dom.spec.whatwg.org/#event)

Event

In all current engines.

Firefox1+Safari1+Chrome1+


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+

[Exposed=(Window,Worker,AudioWorklet)] interface Event { constructor(DOMString type, optional EventInit eventInitDict = {});

readonly attribute DOMString type; readonly attribute EventTarget? target; readonly attribute EventTarget? srcElement; // legacy readonly 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; // legacy undefined 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](https://dom.spec.whatwg.org/#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](https://dom.spec.whatwg.org/#eventtarget) object.

An event has an associated target (a potential event target). Unless stated otherwise it is null.

An event has an associated (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](https://w3c.github.io/touch-events/#idl-def-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](https://dom.spec.whatwg.org/#eventtarget) object), an invocation-target-in-shadow-tree (a boolean), a shadow-adjusted target (a potential event target), a (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/Event

In all current engines.

Firefox11+Safari6+Chrome15+


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+

event = new [Event](https://dom.spec.whatwg.org/#dom-event-event)(type [, eventInitDict])

Returns a new event whose [type](https://dom.spec.whatwg.org/#dom-event-type) attribute value is set to type. The eventInitDict argument allows for setting the [bubbles](https://dom.spec.whatwg.org/#dom-event-bubbles) and [cancelable](https://dom.spec.whatwg.org/#dom-event-cancelable) attributes via object members of the same name.

Event/type

In all current engines.

Firefox1.5+Safari1+Chrome1+


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+

event . `[type](https://dom.spec.whatwg.org/#dom-event-type)`

Returns the type of event, e.g. "click", "hashchange", or "submit".

Event/target

In all current engines.

Firefox1+Safari1+Chrome1+


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+

event . `[target](https://dom.spec.whatwg.org/#dom-event-target)`

Returns the object to which event is dispatched (its target).

Event/currentTarget

In all current engines.

Firefox1+Safari10+Chrome1+


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+

event . `[currentTarget](https://dom.spec.whatwg.org/#dom-event-currenttarget)`

Returns the object whose event listener’s callback is currently being invoked.

Event/composedPath

In all current engines.

Firefox52+Safari10+Chrome53+


Opera40+Edge79+


Edge (Legacy)NoneIENone


Firefox for Android52+iOS Safari10+Chrome for Android53+Android WebView53+Samsung Internet6.0+Opera Mobile41+


Node.js14.5.0+

event . `[composedPath()](https://dom.spec.whatwg.org/#dom-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’s [currentTarget](https://dom.spec.whatwg.org/#dom-event-currenttarget).

Event/eventPhase

In all current engines.

Firefox1.5+Safari4+Chrome45+


Opera32+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari3+Chrome for Android45+Android WebView45+Samsung Internet5.0+Opera Mobile32+


Node.js14.5.0+

event . `[eventPhase](https://dom.spec.whatwg.org/#dom-event-eventphase)`

Returns the event’s phase, which is one of [NONE](https://dom.spec.whatwg.org/#dom-event-none), [CAPTURING_PHASE](https://dom.spec.whatwg.org/#dom-event-capturing_phase), [AT_TARGET](https://dom.spec.whatwg.org/#dom-event-at_target), and [BUBBLING_PHASE](https://dom.spec.whatwg.org/#dom-event-bubbling_phase).

Event/stopPropagation

In all current engines.

Firefox1+Safari1+Chrome1+


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+

event . [stopPropagation](https://dom.spec.whatwg.org/#dom-event-stoppropagation)()

When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object.

Event/stopImmediatePropagation

In all current engines.

Firefox10+Safari5+Chrome6+


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+

event . [stopImmediatePropagation](https://dom.spec.whatwg.org/#dom-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

In all current engines.

Firefox1.5+Safari4+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari3+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile12.1+


Node.js14.5.0+

event . `[bubbles](https://dom.spec.whatwg.org/#dom-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; otherwise false.

Event/cancelable

In all current engines.

Firefox1.5+Safari4+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari3+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile12.1+


Node.js14.5.0+

event . `[cancelable](https://dom.spec.whatwg.org/#dom-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()](https://dom.spec.whatwg.org/#dom-event-preventdefault) method.

Event/preventDefault

In all current engines.

Firefox1+Safari1+Chrome1+


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+

event . [preventDefault](https://dom.spec.whatwg.org/#dom-event-preventdefault)()

If invoked when the [cancelable](https://dom.spec.whatwg.org/#dom-event-cancelable) attribute value is true, and while executing a listener for the event with [passive](https://dom.spec.whatwg.org/#dom-addeventlisteneroptions-passive) set to false, signals to the operation that caused event to be dispatched that it needs to be canceled.

Event/defaultPrevented

In all current engines.

Firefox6+Safari5+Chrome18+


Opera11+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android6+iOS Safari5+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile11+


Node.js14.5.0+

event . `[defaultPrevented](https://dom.spec.whatwg.org/#dom-event-defaultprevented)`

Returns true if [preventDefault()](https://dom.spec.whatwg.org/#dom-event-preventdefault) was invoked successfully to indicate cancelation; otherwise false.

Event/composed

In all current engines.

Firefox52+Safari10+Chrome53+


Opera40+Edge79+


Edge (Legacy)NoneIENone


Firefox for Android52+iOS Safari10+Chrome for Android53+Android WebView53+Samsung Internet6.0+Opera Mobile41+


Node.js14.5.0+

event . `[composed](https://dom.spec.whatwg.org/#dom-event-composed)`

Returns true or false depending on how event was initialized. True if event invokes listeners past a [ShadowRoot](https://dom.spec.whatwg.org/#shadowroot) node that is the root of its target; otherwise false.

Event/isTrusted

In all current engines.

Firefox1.5+Safari10+Chrome46+


Opera33+Edge79+


Edge (Legacy)12+IENone


Firefox for Android4+iOS Safari10+Chrome for Android46+Android WebView46+Samsung Internet5.0+Opera Mobile33+


Node.js14.5.0+

event . `[isTrusted](https://dom.spec.whatwg.org/#dom-event-istrusted)`

Returns true if event was dispatched by the user agent, and false otherwise.

Event/timeStamp

In all current engines.

Firefox1.5+Safari4+Chrome49+


Opera12.1+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari3+Chrome for Android49+Android WebView49+Samsung Internet5.0+Opera Mobile36+


Node.js14.5.0+

event . `[timeStamp](https://dom.spec.whatwg.org/#dom-event-timestamp)`

Returns the event’s timestamp as the number of milliseconds measured relative to the time origin.

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.

The target getter steps are to return this’s target.

The srcElement getter steps are to return this’s target.

The currentTarget attribute must return the value it was initialized to. When an event is created the attribute must be initialized to null.

The composedPath() method steps are:

  1. Let composedPath be an empty list.

  2. Let path be this’s path.

  3. If path is empty, then return composedPath.

  4. Let currentTarget be this’s [currentTarget](https://dom.spec.whatwg.org/#dom-event-currenttarget) attribute value.

  5. Append currentTarget to composedPath.

  6. Let currentTargetIndex be 0.

  7. Let currentTargetHiddenSubtreeLevel be 0.

  8. Let index be path’s size − 1.

  9. While index is greater than or equal to 0:

    1. If path[index]'s root-of-closed-tree is true, then increase currentTargetHiddenSubtreeLevel by 1.

    2. If path[index]'s invocation target is currentTarget, then set currentTargetIndex to index and break.

    3. If path[index]'s slot-in-closed-tree is true, then decrease currentTargetHiddenSubtreeLevel by 1.

    4. Decrease index by 1.

  10. Let currentHiddenLevel and maxHiddenLevel be currentTargetHiddenSubtreeLevel.

  11. Set index to currentTargetIndex − 1.

  12. While index is greater than or equal to 0:

1.  If path\[index\]'s [root-of-closed-tree](https://dom.spec.whatwg.org/#event-path-root-of-closed-tree) is true, then increase currentHiddenLevel by 1.
    
2.  If currentHiddenLevel is less than or equal to maxHiddenLevel, then [prepend](https://infra.spec.whatwg.org/#list-prepend) path\[index\]'s [invocation target](https://dom.spec.whatwg.org/#event-path-invocation-target) to composedPath.
    
3.  If path\[index\]'s [slot-in-closed-tree](https://dom.spec.whatwg.org/#event-path-slot-in-closed-tree) is true, then:
    
    1.  Decrease currentHiddenLevel by 1.
        
    2.  If currentHiddenLevel is less than maxHiddenLevel, then set maxHiddenLevel to currentHiddenLevel.
        
4.  Decrease index by 1.
  1. Set currentHiddenLevel and maxHiddenLevel to currentTargetHiddenSubtreeLevel.

  2. Set index to currentTargetIndex + 1.

  3. While index is less than path’s size:

1.  If path\[index\]'s [slot-in-closed-tree](https://dom.spec.whatwg.org/#event-path-slot-in-closed-tree) is true, then increase currentHiddenLevel by 1.
    
2.  If currentHiddenLevel is less than or equal to maxHiddenLevel, then [append](https://infra.spec.whatwg.org/#list-append) path\[index\]'s [invocation target](https://dom.spec.whatwg.org/#event-path-invocation-target) to composedPath.
    
3.  If path\[index\]'s [root-of-closed-tree](https://dom.spec.whatwg.org/#event-path-root-of-closed-tree) is true, then:
    
    1.  Decrease currentHiddenLevel by 1.
        
    2.  If currentHiddenLevel is less than maxHiddenLevel, then set maxHiddenLevel to currentHiddenLevel.
        
4.  Increase index by 1.
  1. Return composedPath.

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](https://dom.spec.whatwg.org/#dom-event-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

The stopPropagation() method steps are to set this’s stop propagation flag.

The cancelBubble getter steps are to return true if this’s stop propagation flag is set; otherwise false.

Event/cancelBubble

In all current engines.

Firefox53+Safari4+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android53+iOS Safari3+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile12.1+


Node.js14.5.0+

The [cancelBubble](https://dom.spec.whatwg.org/#dom-event-cancelbubble) setter steps are to set this’s stop propagation flag if the given value is true; otherwise do nothing.

The stopImmediatePropagation() method steps are to set this’s stop propagation flag and this’s stop immediate propagation flag.

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](https://dom.spec.whatwg.org/#dom-event-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 getter steps are to return false if this’s canceled flag is set; otherwise true.

The [returnValue](https://dom.spec.whatwg.org/#dom-event-returnvalue) setter steps are to set the canceled flag with this if the given value is false; otherwise do nothing.

The preventDefault() method steps are to set the canceled flag with this.

There are scenarios where invoking [preventDefault()](https://dom.spec.whatwg.org/#dom-event-preventdefault) has no effect. User agents are encouraged to log the precise cause in a developer console, to aid debugging.

The defaultPrevented getter steps are to return true if this’s canceled flag is set; otherwise false.

The composed getter steps are to return true if this’s composed flag is set; otherwise false.


The isTrusted attribute must return the value it was initialized to. When an event is created the attribute must be initialized to false.

[isTrusted](https://dom.spec.whatwg.org/#dom-event-istrusted) is a convenience that indicates whether an event is dispatched by the user agent (as opposed to using [dispatchEvent()](https://dom.spec.whatwg.org/#dom-eventtarget-dispatchevent)). The sole legacy exception is [click()](https://html.spec.whatwg.org/multipage/interaction.html#dom-click), which causes the user agent to dispatch an event whose [isTrusted](https://dom.spec.whatwg.org/#dom-event-istrusted) attribute is initialized to false.

The timeStamp attribute must return the value it was initialized to.


To initialize an event, with type, bubbles, and cancelable, run these steps:

  1. Set event’s initialized flag.

  2. Unset event’s stop propagation flag, stop immediate propagation flag, and canceled flag.

  3. Set event’s [isTrusted](https://dom.spec.whatwg.org/#dom-event-istrusted) attribute to false.

  4. Set event’s target to null.

  5. Set event’s [type](https://dom.spec.whatwg.org/#dom-event-type) attribute to type.

  6. Set event’s [bubbles](https://dom.spec.whatwg.org/#dom-event-bubbles) attribute to bubbles.

  7. Set event’s [cancelable](https://dom.spec.whatwg.org/#dom-event-cancelable) attribute to cancelable.

The initEvent(type, bubbles, cancelable) method steps are:

  1. If this’s dispatch flag is set, then return.

  2. Initialize this with type, bubbles, and cancelable.

[initEvent()](https://dom.spec.whatwg.org/#dom-event-initevent) is redundant with event constructors and incapable of setting [composed](https://dom.spec.whatwg.org/#dom-event-composed). It has to be supported for legacy content.

2.3. Legacy extensions to the [Window](https://html.spec.whatwg.org/multipage/window-object.html#window) interface

partial interface Window { [Replaceable] readonly attribute (Event or undefined) event; // legacy };

Each [Window](https://html.spec.whatwg.org/multipage/window-object.html#window) object has an associated current event (undefined or an [Event](https://dom.spec.whatwg.org/#event) object). Unless stated otherwise it is undefined.

The event getter steps are to return this’s current event.

Web developers are strongly encouraged to instead rely on the [Event](https://dom.spec.whatwg.org/#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](https://dom.spec.whatwg.org/#customevent)

CustomEvent

In all current engines.

Firefox6+Safari5+Chrome15+


Opera11+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android6+iOS Safari5+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile11+

[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](https://dom.spec.whatwg.org/#customevent) interface can be used to carry custom data.

CustomEvent/CustomEvent

In all current engines.

Firefox11+Safari6+Chrome15+


Opera11.6+Edge79+


Edge (Legacy)12+IENone


Firefox for Android14+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile12+

event = new [CustomEvent](https://dom.spec.whatwg.org/#dom-customevent-customevent)(type [, eventInitDict])

Works analogously to the constructor for [Event](https://dom.spec.whatwg.org/#event) except that the eventInitDict argument now allows for setting the [detail](https://dom.spec.whatwg.org/#dom-customevent-detail) attribute too.

CustomEvent/detail

In all current engines.

Firefox11+Safari5+Chrome15+


Opera11.6+Edge79+


Edge (Legacy)12+IENone


Firefox for Android14+iOS Safari5+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile12+

event . `[detail](https://dom.spec.whatwg.org/#dom-customevent-detail)`

Returns any custom data event was created with. Typically used for synthetic events.

The detail attribute must return the value it was initialized to.

The initCustomEvent(type, bubbles, cancelable, detail) method steps are:

  1. If this’s dispatch flag is set, then return.

  2. Initialize this with type, bubbles, and cancelable.

  3. Set this’s [detail](https://dom.spec.whatwg.org/#dom-customevent-detail) attribute to detail.

2.5. Constructing events

Specifications may define event constructing steps for all or some events. The algorithm is passed an event event and an [EventInit](https://dom.spec.whatwg.org/#dictdef-eventinit) eventInitDict as indicated in the inner event creation steps.

This construct can be used by [Event](https://dom.spec.whatwg.org/#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](https://dom.spec.whatwg.org/#event) interface, or of an interface that inherits from the [Event](https://dom.spec.whatwg.org/#event) interface, is invoked, these steps must be run, given the arguments type and eventInitDict:

  1. Let event be the result of running the inner event creation steps with this interface, null, now, and eventInitDict.

  2. Initialize event’s [type](https://dom.spec.whatwg.org/#dom-event-type) attribute to type.

  3. Return event.

To create an event using eventInterface, which must be either [Event](https://dom.spec.whatwg.org/#event) or an interface that inherits from it, and optionally given a Realm realm, run these steps:

  1. If realm is not given, then set it to null.

  2. 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](https://dom.spec.whatwg.org/#dictdef-eventinit) or a dictionary that inherits from it.)

    This does not work if members are required; see whatwg/dom#600.

  3. 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 of NSEvent objects.

  4. Initialize event’s [isTrusted](https://dom.spec.whatwg.org/#dom-event-istrusted) attribute to true.

  5. 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:

  1. 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 whatwg/webidl#135.

  2. Set event’s initialized flag.

  3. Initialize event’s [timeStamp](https://dom.spec.whatwg.org/#dom-event-timestamp) attribute to the relative high resolution coarse time given time and event’s relevant global object.

  4. For each member → value in dictionary, if event has an attribute whose identifier is member, then initialize that attribute to value.

  5. Run the event constructing steps with event and dictionary.

  6. Return event.

2.6. Defining event interfaces

In general, when defining a new interface that inherits from [Event](https://dom.spec.whatwg.org/#event) please always ask feedback from the WHATWG or the W3C WebApps WG community.

The [CustomEvent](https://dom.spec.whatwg.org/#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](https://dom.spec.whatwg.org/#event) interface that have such a method only have it for historical reasons.

2.7. Interface [EventTarget](https://dom.spec.whatwg.org/#eventtarget)

EventTarget

In all current engines.

Firefox1+Safari1+Chrome1+


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+

EventListener/handleEvent

In all current engines.

Firefox1+Safari1+Chrome1+


Opera7+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

EventListener

In all current engines.

Firefox1+Safari1+Chrome1+


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](https://dom.spec.whatwg.org/#eventtarget) object represents a target to which an event can be dispatched when something has occurred.

Each [EventTarget](https://dom.spec.whatwg.org/#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](https://dom.spec.whatwg.org/#callbackdef-eventlistener) object)
  • capture (a boolean, initially false)
  • passive (a boolean, initially false)
  • once (a boolean, initially false)
  • signal (null or an [AbortSignal](https://dom.spec.whatwg.org/#abortsignal) object)
  • removed (a boolean for bookkeeping purposes, initially false)

Although callback is an [EventListener](https://dom.spec.whatwg.org/#callbackdef-eventlistener) object, an event listener is a broader concept as can be seen above.

Each [EventTarget](https://dom.spec.whatwg.org/#eventtarget) object also has an associated get the parent algorithm, which takes an event event, and returns an [EventTarget](https://dom.spec.whatwg.org/#eventtarget) object. Unless specified otherwise it returns null.

Nodes, shadow roots, and documents override the get the parent algorithm.

Each [EventTarget](https://dom.spec.whatwg.org/#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](https://dom.spec.whatwg.org/#eventtarget) objects, e.g., the [area](https://html.spec.whatwg.org/multipage/image-maps.html#the-area-element) element, in response to synthetic [MouseEvent](https://www.w3.org/TR/uievents/#mouseevent) events whose [type](https://dom.spec.whatwg.org/#dom-event-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](https://dom.spec.whatwg.org/#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](https://html.spec.whatwg.org/multipage/input.html#the-input-element) elements and are not to be used for anything else. [HTML]

EventTarget/EventTarget

In all current engines.

Firefox59+Safari14+Chrome64+


Opera51+Edge79+


Edge (Legacy)NoneIENone


Firefox for Android59+iOS Safari14+Chrome for Android64+Android WebView64+Samsung Internet9.0+Opera Mobile47+


Node.js15.0.0+

target = new [EventTarget](https://dom.spec.whatwg.org/#dom-eventtarget-eventtarget)();

Creates a new [EventTarget](https://dom.spec.whatwg.org/#eventtarget) object, which can be used by developers to dispatch and listen for events.

EventTarget/addEventListener

In all current engines.

Firefox1+Safari1+Chrome1+


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+

target . [addEventListener](https://dom.spec.whatwg.org/#dom-eventtarget-addeventlistener)(type, callback [, options])

Appends an event listener for events whose [type](https://dom.spec.whatwg.org/#dom-event-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](https://dom.spec.whatwg.org/#dom-eventlisteneroptions-capture).

When set to true, options’s [capture](https://dom.spec.whatwg.org/#dom-eventlisteneroptions-capture) prevents callback from being invoked when the event’s [eventPhase](https://dom.spec.whatwg.org/#dom-event-eventphase) attribute value is [BUBBLING_PHASE](https://dom.spec.whatwg.org/#dom-event-bubbling_phase). When false (or not present), callback will not be invoked when event’s [eventPhase](https://dom.spec.whatwg.org/#dom-event-eventphase) attribute value is [CAPTURING_PHASE](https://dom.spec.whatwg.org/#dom-event-capturing_phase). Either way, callback will be invoked if event’s [eventPhase](https://dom.spec.whatwg.org/#dom-event-eventphase) attribute value is [AT_TARGET](https://dom.spec.whatwg.org/#dom-event-at_target).

When set to true, options’s [passive](https://dom.spec.whatwg.org/#dom-addeventlisteneroptions-passive) indicates that the callback will not cancel the event by invoking [preventDefault()](https://dom.spec.whatwg.org/#dom-event-preventdefault). This is used to enable performance optimizations described in § 2.8 Observing event listeners.

When set to true, options’s [once](https://dom.spec.whatwg.org/#dom-addeventlisteneroptions-once) indicates that the callback will only be invoked once after which the event listener will be removed.

If an [AbortSignal](https://dom.spec.whatwg.org/#abortsignal) is passed for options’s [signal](https://dom.spec.whatwg.org/#dom-addeventlisteneroptions-signal), 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.

EventTarget/removeEventListener

In all current engines.

Firefox1+Safari1+Chrome1+


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+

target . [removeEventListener](https://dom.spec.whatwg.org/#dom-eventtarget-removeeventlistener)(type, callback [, options])

Removes the event listener in target’s event listener list with the same type, callback, and options.

EventTarget/dispatchEvent

In all current engines.

Firefox2+Safari3.1+Chrome4+


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+

target . [dispatchEvent](https://dom.spec.whatwg.org/#dom-eventtarget-dispatchevent)(event)

Dispatches a synthetic event event to target and returns true if either event’s [cancelable](https://dom.spec.whatwg.org/#dom-event-cancelable) attribute value is false or its [preventDefault()](https://dom.spec.whatwg.org/#dom-event-preventdefault) method was not invoked; otherwise false.

To flatten options, run these steps:

  1. If options is a boolean, then return options.

  2. Return options["[capture](https://dom.spec.whatwg.org/#dom-eventlisteneroptions-capture)"].

To flatten more options, run these steps:

  1. Let capture be the result of flattening options.

  2. Let once and passive be false.

  3. Let signal be null.

  4. If options is a dictionary, then:

    1. Set passive to options["[passive](https://dom.spec.whatwg.org/#dom-addeventlisteneroptions-passive)"] and once to options["[once](https://dom.spec.whatwg.org/#dom-addeventlisteneroptions-once)"].

    2. If options["[signal](https://dom.spec.whatwg.org/#dom-addeventlisteneroptions-signal)"] exists, then set signal to options["[signal](https://dom.spec.whatwg.org/#dom-addeventlisteneroptions-signal)"].

  5. Return capture, passive, once, and signal.

The new EventTarget() constructor steps are to do nothing.

Because of the defaults stated elsewhere, the returned [EventTarget](https://dom.spec.whatwg.org/#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](https://dom.spec.whatwg.org/#eventtarget)s do not participate in a tree structure.

To add an event listener, given an [EventTarget](https://dom.spec.whatwg.org/#eventtarget) object eventTarget and an event listener listener, run these steps:

  1. If eventTarget is a [ServiceWorkerGlobalScope](https://w3c.github.io/ServiceWorker/#serviceworkerglobalscope) object, its service worker’s script resource’s has ever been evaluated flag is set, and listener’s type matches the [type](https://dom.spec.whatwg.org/#dom-event-type) 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]

  2. If listener’s signal is not null and is aborted, then return.

  3. If listener’s callback is null, then return.

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

  5. If listener’s signal is not null, then add the following abort steps to it:

    1. 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]

The addEventListener(type, callback, options) method steps are:

  1. Let capture, passive, once, and signal be the result of flattening more options.

  2. 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](https://dom.spec.whatwg.org/#eventtarget) object eventTarget and an event listener listener, run these steps:

  1. If eventTarget is a [ServiceWorkerGlobalScope](https://w3c.github.io/ServiceWorker/#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]

  2. 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](https://dom.spec.whatwg.org/#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]

The removeEventListener(type, callback, options) method steps are:

  1. Let capture be the result of flattening options.

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

The dispatchEvent(event) method steps are:

  1. If event’s dispatch flag is set, or if its initialized flag is not set, then throw an "[InvalidStateError](https://webidl.spec.whatwg.org/#invalidstateerror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  2. Initialize event’s [isTrusted](https://dom.spec.whatwg.org/#dom-event-istrusted) attribute to false.

  3. 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](https://dom.spec.whatwg.org/#dom-event-cancelable) only when there is at least one non-[passive](https://dom.spec.whatwg.org/#dom-addeventlisteneroptions-passive) listener. For example, non-[passive](https://dom.spec.whatwg.org/#dom-addeventlisteneroptions-passive) [TouchEvent](https://w3c.github.io/touch-events/#idl-def-touchevent) listeners must block scrolling, but if all listeners are [passive](https://dom.spec.whatwg.org/#dom-addeventlisteneroptions-passive) then scrolling can be allowed to start in parallel by making the [TouchEvent](https://w3c.github.io/touch-events/#idl-def-touchevent) uncancelable (so that calls to [preventDefault()](https://dom.spec.whatwg.org/#dom-event-preventdefault) are ignored). So code dispatching an event is able to observe the absence of non-[passive](https://dom.spec.whatwg.org/#dom-addeventlisteneroptions-passive) listeners, and use that to clear the [cancelable](https://dom.spec.whatwg.org/#dom-event-cancelable) property of the event being dispatched.

Ideally, any new event APIs are defined such that they do not need this property. (Use whatwg/dom 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:

  1. Set event’s dispatch flag.

  2. 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](https://html.spec.whatwg.org/multipage/window-object.html#window) object.

  3. Let activationTarget be null.

  4. Let relatedTarget be the result of retargeting event’s relatedTarget against target.

  5. If target is not relatedTarget or target is event’s relatedTarget, then:

    1. Let touchTargets be a new list.

    2. For each touchTarget of event’s touch target list, append the result of retargeting touchTarget against target to touchTargets.

    3. Append to an event path with event, target, targetOverride, relatedTarget, touchTargets, and false.

    4. Let isActivationEvent be true, if event is a [MouseEvent](https://www.w3.org/TR/uievents/#mouseevent) object and event’s [type](https://dom.spec.whatwg.org/#dom-event-type) attribute is "click"; otherwise false.

    5. If isActivationEvent is true and target has activation behavior, then set activationTarget to target.

    6. Let slottable be target, if target is a slottable and is assigned, and null otherwise.

    7. Let slot-in-closed-tree be false.

    8. Let parent be the result of invoking target’s get the parent with event.

    9. While parent is non-null:

      1. If slottable is non-null:

        1. Assert: parent is a slot.

        2. Set slottable to null.

        3. If parent’s root is a shadow root whose mode is "closed", then set slot-in-closed-tree to true.

      2. If parent is a slottable and is assigned, then set slottable to parent.

      3. Let relatedTarget be the result of retargeting event’s relatedTarget against parent.

      4. Let touchTargets be a new list.

      5. For each touchTarget of event’s touch target list, append the result of retargeting touchTarget against parent to touchTargets.

      6. If parent is a [Window](https://html.spec.whatwg.org/multipage/window-object.html#window) object, or parent is a node and target’s root is a shadow-including inclusive ancestor of parent, then:

        1. If isActivationEvent is true, event’s [bubbles](https://dom.spec.whatwg.org/#dom-event-bubbles) attribute is true, activationTarget is null, and parent has activation behavior, then set activationTarget to parent.

        2. Append to an event path with event, parent, null, relatedTarget, touchTargets, and slot-in-closed-tree.

      7. Otherwise, if parent is relatedTarget, then set parent to null.

      8. Otherwise, set target to parent and then:

        1. If isActivationEvent is true, activationTarget is null, and target has activation behavior, then set activationTarget to target.

        2. Append to an event path with event, parent, target, relatedTarget, touchTargets, and slot-in-closed-tree.

      9. If parent is non-null, then set parent to the result of invoking parent’s get the parent with event.

      10. Set slot-in-closed-tree to false.

    10. Let clearTargetsStruct be the last struct in event’s path whose shadow-adjusted target is non-null.

    11. Let clearTargets be true if clearTargetsStruct’s shadow-adjusted target, clearTargetsStruct’s relatedTarget, or an [EventTarget](https://dom.spec.whatwg.org/#eventtarget) object in clearTargetsStruct’s touch target list is a node and its root is a shadow root; otherwise false.

    12. If activationTarget is non-null and activationTarget has legacy-pre-activation behavior, then run activationTarget’s legacy-pre-activation behavior.

    13. For each struct in event’s path, in reverse order:

    1.  If struct’s [shadow-adjusted target](https://dom.spec.whatwg.org/#event-path-shadow-adjusted-target) is non-null, then set event’s `[eventPhase](https://dom.spec.whatwg.org/#dom-event-eventphase)` attribute to `[AT_TARGET](https://dom.spec.whatwg.org/#dom-event-at_target)`.
        
    2.  Otherwise, set event’s `[eventPhase](https://dom.spec.whatwg.org/#dom-event-eventphase)` attribute to `[CAPTURING_PHASE](https://dom.spec.whatwg.org/#dom-event-capturing_phase)`.
        
    3.  [Invoke](https://dom.spec.whatwg.org/#concept-event-listener-invoke) with struct, event, "`capturing`", and legacyOutputDidListenersThrowFlag if given.
    
    1. For each struct in event’s path:
    1.  If struct’s [shadow-adjusted target](https://dom.spec.whatwg.org/#event-path-shadow-adjusted-target) is non-null, then set event’s `[eventPhase](https://dom.spec.whatwg.org/#dom-event-eventphase)` attribute to `[AT_TARGET](https://dom.spec.whatwg.org/#dom-event-at_target)`.
        
    2.  Otherwise:
        
        1.  If event’s `[bubbles](https://dom.spec.whatwg.org/#dom-event-bubbles)` attribute is false, then [continue](https://infra.spec.whatwg.org/#iteration-continue).
            
        2.  Set event’s `[eventPhase](https://dom.spec.whatwg.org/#dom-event-eventphase)` attribute to `[BUBBLING_PHASE](https://dom.spec.whatwg.org/#dom-event-bubbling_phase)`.
            
    3.  [Invoke](https://dom.spec.whatwg.org/#concept-event-listener-invoke) with struct, event, "`bubbling`", and legacyOutputDidListenersThrowFlag if given.
    
  6. Set event’s [eventPhase](https://dom.spec.whatwg.org/#dom-event-eventphase) attribute to [NONE](https://dom.spec.whatwg.org/#dom-event-none).

  7. Set event’s [currentTarget](https://dom.spec.whatwg.org/#dom-event-currenttarget) attribute to null.

  8. Set event’s path to the empty list.

  9. Unset event’s dispatch flag, stop propagation flag, and stop immediate propagation flag.

  10. If clearTargets, then:

1.  Set event’s [target](https://dom.spec.whatwg.org/#event-target) to null.
    
2.  Set event’s [relatedTarget](https://dom.spec.whatwg.org/#event-relatedtarget) to null.
    
3.  Set event’s [touch target list](https://dom.spec.whatwg.org/#event-touch-target-list) to the empty list.
  1. If activationTarget is non-null, then:
1.  If event’s [canceled flag](https://dom.spec.whatwg.org/#canceled-flag) is unset, then run activationTarget’s [activation behavior](https://dom.spec.whatwg.org/#eventtarget-activation-behavior) with event.
    
2.  Otherwise, if activationTarget has [legacy-canceled-activation behavior](https://dom.spec.whatwg.org/#eventtarget-legacy-canceled-activation-behavior), then run activationTarget’s [legacy-canceled-activation behavior](https://dom.spec.whatwg.org/#eventtarget-legacy-canceled-activation-behavior).
  1. Return false if event’s canceled flag is set; otherwise true.

To append to an event path, given an event, invocationTarget, shadowAdjustedTarget, relatedTarget, touchTargets, and a slot-in-closed-tree, run these steps:

  1. Let invocationTargetInShadowTree be false.

  2. If invocationTarget is a node and its root is a shadow root, then set invocationTargetInShadowTree to true.

  3. Let root-of-closed-tree be false.

  4. If invocationTarget is a shadow root whose mode is "closed", then set root-of-closed-tree to true.

  5. 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:

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

  2. Set event’s relatedTarget to struct’s relatedTarget.

  3. Set event’s touch target list to struct’s touch target list.

  4. If event’s stop propagation flag is set, then return.

  5. Initialize event’s [currentTarget](https://dom.spec.whatwg.org/#dom-event-currenttarget) attribute to struct’s invocation target.

  6. Let listeners be a clone of event’s [currentTarget](https://dom.spec.whatwg.org/#dom-event-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.

  7. Let invocationTargetInShadowTree be struct’s invocation-target-in-shadow-tree.

  8. Let found be the result of running inner invoke with event, listeners, phase, invocationTargetInShadowTree, and legacyOutputDidListenersThrowFlag if given.

  9. If found is false and event’s [isTrusted](https://dom.spec.whatwg.org/#dom-event-istrusted) attribute is true, then:

    1. Let originalEventType be event’s [type](https://dom.spec.whatwg.org/#dom-event-type) attribute value.

    2. If event’s [type](https://dom.spec.whatwg.org/#dom-event-type) attribute value is a match for any of the strings in the first column in the following table, set event’s [type](https://dom.spec.whatwg.org/#dom-event-type) 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"

    3. Inner invoke with event, listeners, phase, invocationTargetInShadowTree, and legacyOutputDidListenersThrowFlag if given.

    4. Set event’s [type](https://dom.spec.whatwg.org/#dom-event-type) attribute value to originalEventType.

To inner invoke, given an event, listeners, phase, invocationTargetInShadowTree, and an optional legacyOutputDidListenersThrowFlag, run these steps:

  1. Let found be false.

  2. For each listener in listeners, whose removed is false:

    1. If event’s [type](https://dom.spec.whatwg.org/#dom-event-type) attribute value is not listener’s type, then continue.

    2. Set found to true.

    3. If phase is "capturing" and listener’s capture is false, then continue.

    4. If phase is "bubbling" and listener’s capture is true, then continue.

    5. If listener’s once is true, then remove listener from event’s [currentTarget](https://dom.spec.whatwg.org/#dom-event-currenttarget) attribute value’s event listener list.

    6. Let global be listener callback’s associated Realm’s global object.

    7. Let currentEvent be undefined.

    8. If global is a [Window](https://html.spec.whatwg.org/multipage/window-object.html#window) object, then:

      1. Set currentEvent to global’s current event.

      2. If invocationTargetInShadowTree is false, then set global’s current event to event.

    9. If listener’s passive is true, then set event’s in passive listener flag.

    10. Call a user object’s operation with listener’s callback, "handleEvent", « event », and event’s [currentTarget](https://dom.spec.whatwg.org/#dom-event-currenttarget) attribute value. If this throws an exception, then:

    1.  [Report the exception](https://html.spec.whatwg.org/multipage/webappapis.html#report-the-exception).
        
    2.  Set legacyOutputDidListenersThrowFlag if given.
        
        The legacyOutputDidListenersThrowFlag is only used by Indexed Database API. [\[INDEXEDDB\]](https://dom.spec.whatwg.org/#biblio-indexeddb)
    
    1. Unset event’s in passive listener flag.

    2. If global is a [Window](https://html.spec.whatwg.org/multipage/window-object.html#window) object, then set global’s current event to currentEvent.

    3. If event’s stop immediate propagation flag is set, then return found.

  3. 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:

  1. If eventConstructor is not given, then let eventConstructor be [Event](https://dom.spec.whatwg.org/#event).

  2. Let event be the result of creating an event given eventConstructor, in the relevant Realm of target.

  3. Initialize event’s [type](https://dom.spec.whatwg.org/#dom-event-type) attribute to e.

  4. Initialize any other IDL attributes of event as described in the invocation of this algorithm.

    This also allows for the [isTrusted](https://dom.spec.whatwg.org/#dom-event-istrusted) attribute to be set to false.

  5. 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](https://dom.spec.whatwg.org/#dom-event-bubbles) or [cancelable](https://dom.spec.whatwg.org/#dom-event-cancelable) attribute initialized, one could write "fire an event named submit at target with its [cancelable](https://dom.spec.whatwg.org/#dom-event-cancelable) attribute initialized to true".

Or, when a custom constructor is needed, "fire an event named click at target using [MouseEvent](https://www.w3.org/TR/uievents/#mouseevent) with its [detail](https://www.w3.org/TR/uievents/#dom-uievent-detail) attribute initialized to 1".

Occasionally the return value is important:

  1. Let doAction be the result of firing an event named like at target.

  2. 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()](https://dom.spec.whatwg.org/#dom-event-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](https://dom.spec.whatwg.org/#abortcontroller) is meant to support these requirements by providing an [abort()](https://dom.spec.whatwg.org/#dom-abortcontroller-abort) method that toggles the state of a corresponding [AbortSignal](https://dom.spec.whatwg.org/#abortsignal) object. The API which wishes to support aborting can accept an [AbortSignal](https://dom.spec.whatwg.org/#abortsignal) object, and use its state to determine how to proceed.

APIs that rely upon [AbortController](https://dom.spec.whatwg.org/#abortcontroller) are encouraged to respond to [abort()](https://dom.spec.whatwg.org/#dom-abortcontroller-abort) by rejecting any unsettled promise with the [AbortSignal](https://dom.spec.whatwg.org/#abortsignal)'s abort reason.

A hypothetical doAmazingness({ ... }) method could accept an [AbortSignal](https://dom.spec.whatwg.org/#abortsignal) object 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}) {
  return new Promise((resolve, reject) => {
    signal.throwIfAborted();

    // Begin doing amazingness, and call resolve(result) when done.
    // But also, watch for signals:
    signal.addEventListener('abort', () => {
      // Stop doing amazingness, and:
      reject(signal.reason);
    });
  });
}

APIs that do not return promises can either react in an equivalent manner or opt to not surface the [AbortSignal](https://dom.spec.whatwg.org/#abortsignal)'s abort reason at all. [addEventListener()](https://dom.spec.whatwg.org/#dom-eventtarget-addeventlistener) is an example of an API where the latter made sense.

APIs that require more granular control could extend both [AbortController](https://dom.spec.whatwg.org/#abortcontroller) and [AbortSignal](https://dom.spec.whatwg.org/#abortsignal) objects according to their needs.

3.1. Interface [AbortController](https://dom.spec.whatwg.org/#abortcontroller)

AbortController

In all current engines.

Firefox57+Safari12.1+Chrome66+


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(optional any reason); };

AbortController/AbortController

In all current engines.

Firefox57+Safari12.1+Chrome66+


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+

AbortController/abort

In all current engines.

Firefox57+Safari12.1+Chrome66+


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+

controller = new [AbortController](https://dom.spec.whatwg.org/#dom-abortcontroller-abortcontroller)()

Returns a new controller whose [signal](https://dom.spec.whatwg.org/#dom-abortcontroller-signal) is set to a newly created [AbortSignal](https://dom.spec.whatwg.org/#abortsignal) object.

AbortController/signal

In all current engines.

Firefox57+Safari12.1+Chrome66+


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+

controller . [signal](https://dom.spec.whatwg.org/#dom-abortcontroller-signal)

Returns the [AbortSignal](https://dom.spec.whatwg.org/#abortsignal) object associated with this object.

controller . [abort](https://dom.spec.whatwg.org/#dom-abortcontroller-abort)(reason)

Invoking this method will store reason in this object’s [AbortSignal](https://dom.spec.whatwg.org/#abortsignal)'s abort reason, and signal to any observers that the associated activity is to be aborted. If reason is undefined, then an "[AbortError](https://webidl.spec.whatwg.org/#aborterror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException) will be stored.

An [AbortController](https://dom.spec.whatwg.org/#abortcontroller) object has an associated signal (an [AbortSignal](https://dom.spec.whatwg.org/#abortsignal) object).

The new AbortController() constructor steps are:

  1. Let signal be a new [AbortSignal](https://dom.spec.whatwg.org/#abortsignal) object.

  2. Set this’s signal to signal.

The signal getter steps are to return this’s signal.

The abort(reason) method steps are to signal abort on this’s signal with reason if it is given.

3.2. Interface [AbortSignal](https://dom.spec.whatwg.org/#abortsignal)

AbortSignal

In all current engines.

Firefox57+Safari11.1+Chrome66+


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 { [NewObject] static AbortSignal abort(optional any reason);

readonly attribute boolean aborted; readonly attribute any reason; undefined throwIfAborted();

attribute EventHandler onabort; };

AbortSignal/abort

In all current engines.

Firefox88+Safari15+Chrome93+


Opera79+Edge93+


Edge (Legacy)NoneIENone


Firefox for Android88+iOS Safari15+Chrome for Android93+Android WebView93+Samsung InternetNoneOpera MobileNone


Node.jsNone

AbortSignal . [abort](https://dom.spec.whatwg.org/#dom-abortsignal-abort)(reason)

Returns an [AbortSignal](https://dom.spec.whatwg.org/#abortsignal) instance whose abort reason is set to reason if not undefined; otherwise to an "[AbortError](https://webidl.spec.whatwg.org/#aborterror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

AbortSignal/aborted

In all current engines.

Firefox57+Safari11.1+Chrome66+


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+

signal . [aborted](https://dom.spec.whatwg.org/#dom-abortsignal-aborted)

Returns true if signal’s [AbortController](https://dom.spec.whatwg.org/#abortcontroller) has signaled to abort; otherwise false.

signal . [reason](https://dom.spec.whatwg.org/#dom-abortsignal-reason)

Returns signal’s abort reason.

signal . [throwIfAborted](https://dom.spec.whatwg.org/#dom-abortsignal-throwifaborted)()

Throws signal’s abort reason, if signal’s [AbortController](https://dom.spec.whatwg.org/#abortcontroller) has signaled to abort; otherwise, does nothing.

An [AbortSignal](https://dom.spec.whatwg.org/#abortsignal) object has an associated abort reason, which is a JavaScript value. It is undefined unless specified otherwise.

An [AbortSignal](https://dom.spec.whatwg.org/#abortsignal) object is aborted when its abort reason is not undefined.

An [AbortSignal](https://dom.spec.whatwg.org/#abortsignal) object has associated abort algorithms, which is a set of algorithms which are to be executed when it is aborted. Unless specified otherwise, its value is the empty set.

To add an algorithm algorithm to an [AbortSignal](https://dom.spec.whatwg.org/#abortsignal) object signal, run these steps:

  1. If signal is aborted, then return.

  2. Append algorithm to signal’s abort algorithms.

To remove an algorithm algorithm from an [AbortSignal](https://dom.spec.whatwg.org/#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()](https://dom.spec.whatwg.org/#dom-abortcontroller-abort). For example, a given API’s abort reason might need to be propagated to a cross-thread environment, such as a service worker.

The static abort(reason) method steps are:

  1. Let signal be a new [AbortSignal](https://dom.spec.whatwg.org/#abortsignal) object.

  2. Set signal’s abort reason to reason if it is given; otherwise to a new "[AbortError](https://webidl.spec.whatwg.org/#aborterror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  3. Return signal.

The aborted getter steps are to return true if this is aborted; otherwise false.

The reason getter steps are to return this’s abort reason.

The throwIfAborted() method steps are to throw this’s abort reason, if this is aborted.

This method is primarily useful for when functions accepting [AbortSignal](https://dom.spec.whatwg.org/#abortsignal)s want to throw (or return a rejected promise) at specific checkpoints, instead of passing along the [AbortSignal](https://dom.spec.whatwg.org/#abortsignal) to other methods. For example, the following function allows aborting in between each attempt to poll for a condition. This gives opportunities to abort the polling process, even though the actual asynchronous operation (i.e., await func()) does not accept an [AbortSignal](https://dom.spec.whatwg.org/#abortsignal).

async function waitForCondition(func, targetValue, { signal } = {}) { while (true) { signal?.throwIfAborted();

const result \= await func();
if (result \=== targetValue) {
  return;
}

} }

AbortSignal/abort_event

In all current engines.

Firefox57+Safari11.1+Chrome66+


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+

AbortSignal/onabort

In all current engines.

Firefox57+Safari11.1+Chrome66+


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](https://dom.spec.whatwg.org/#abortsignal) object represent the wishes of the corresponding [AbortController](https://dom.spec.whatwg.org/#abortcontroller) object, but an API observing the [AbortSignal](https://dom.spec.whatwg.org/#abortsignal) object can chose to ignore them. For instance, if the operation has already completed.

To signal abort, given an [AbortSignal](https://dom.spec.whatwg.org/#abortsignal) object signal and an optional reason, run these steps:

  1. If signal is aborted, then return.

  2. Set signal’s abort reason to reason if it is given; otherwise to a new "[AbortError](https://webidl.spec.whatwg.org/#aborterror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  3. For each algorithm in signal’s abort algorithms: run algorithm.

  4. Empty signal’s abort algorithms.

  5. Fire an event named [abort](https://dom.spec.whatwg.org/#eventdef-abortsignal-abort) at signal.

A followingSignal (an [AbortSignal](https://dom.spec.whatwg.org/#abortsignal)) is made to follow a parentSignal (an [AbortSignal](https://dom.spec.whatwg.org/#abortsignal)) by running these steps:

  1. If followingSignal is aborted, then return.

  2. If parentSignal is aborted, then signal abort on followingSignal with parentSignal’s abort reason.

  3. Otherwise, add the following abort steps to parentSignal:

    1. Signal abort on followingSignal with parentSignal’s abort reason.

3.3. Using [AbortController](https://dom.spec.whatwg.org/#abortcontroller) and [AbortSignal](https://dom.spec.whatwg.org/#abortsignal) objects in APIs

Any web platform API using promises to represent operations that can be aborted must adhere to the following:

  • Accept [AbortSignal](https://dom.spec.whatwg.org/#abortsignal) objects through a signal dictionary member.
  • Convey that the operation got aborted by rejecting the promise with [AbortSignal](https://dom.spec.whatwg.org/#abortsignal) object’s abort reason.
  • Reject immediately if the [AbortSignal](https://dom.spec.whatwg.org/#abortsignal) is already aborted, otherwise:
  • Use the abort algorithms mechanism to observe changes to the [AbortSignal](https://dom.spec.whatwg.org/#abortsignal) object and do so in a manner that does not lead to clashes with other observers.

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:

Aliens? Why yes.

It is represented as follows:

  • Document
    • Doctype: html
    • [Element](https://dom.spec.whatwg.org/#element): html class="e"
      • [Element](https://dom.spec.whatwg.org/#element): head
        • [Element](https://dom.spec.whatwg.org/#element): title
          • [Text](https://dom.spec.whatwg.org/#text): Aliens?
      • [Text](https://dom.spec.whatwg.org/#text): ⏎␣
      • [Element](https://dom.spec.whatwg.org/#element): body
        • [Text](https://dom.spec.whatwg.org/#text): Why yes.⏎

Note that, due to the magic that is HTML parsing, not all ASCII whitespace were turned into [Text](https://dom.spec.whatwg.org/#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

Nodes are objects that implement [Node](https://dom.spec.whatwg.org/#node). Nodes participate in a tree, which is known as the node tree.

For brevity, this specification refers to an object that implements [Node](https://dom.spec.whatwg.org/#node) and an inherited interface NodeInterface, as a NodeInterface node.

A node tree is constrained as follows, expressed as a relationship between a node and its potential children:

[Document](https://dom.spec.whatwg.org/#document)

In tree order:

  1. Zero or more [ProcessingInstruction](https://dom.spec.whatwg.org/#processinginstruction) or [Comment](https://dom.spec.whatwg.org/#comment) nodes.

  2. Optionally one [DocumentType](https://dom.spec.whatwg.org/#documenttype) node.

  3. Zero or more [ProcessingInstruction](https://dom.spec.whatwg.org/#processinginstruction) or [Comment](https://dom.spec.whatwg.org/#comment) nodes.

  4. Optionally one [Element](https://dom.spec.whatwg.org/#element) node.

  5. Zero or more [ProcessingInstruction](https://dom.spec.whatwg.org/#processinginstruction) or [Comment](https://dom.spec.whatwg.org/#comment) nodes.

[DocumentFragment](https://dom.spec.whatwg.org/#documentfragment)

[Element](https://dom.spec.whatwg.org/#element)

Zero or more [Element](https://dom.spec.whatwg.org/#element) or [CharacterData](https://dom.spec.whatwg.org/#characterdata) nodes.

[DocumentType](https://dom.spec.whatwg.org/#documenttype)

[CharacterData](https://dom.spec.whatwg.org/#characterdata)

[Attr](https://dom.spec.whatwg.org/#attr)

No children.

[Attr](https://dom.spec.whatwg.org/#attr) nodes participate in a tree for historical reasons; they never have a (non-null) parent or any children and are therefore alone in a tree.

To determine the length of a node node, run these steps:

  1. If node is a [DocumentType](https://dom.spec.whatwg.org/#documenttype) or [Attr](https://dom.spec.whatwg.org/#attr) node, then return 0.

  2. If node is a [CharacterData](https://dom.spec.whatwg.org/#characterdata) node, then return node’s data’s length.

  3. Return the number of node’s children.

A node is considered empty if its length is 0.

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; otherwise null.

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

Element/slot

In all current engines.

Firefox63+Safari10+Chrome53+


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](https://html.spec.whatwg.org/multipage/scripting.html#the-slot-element) 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:

  1. If element is a slot, localName is name, and namespace is null, then:

    1. If value is oldValue, then return.

    2. If value is null and oldValue is the empty string, then return.

    3. If value is the empty string and oldValue is null, then return.

    4. If value is null or the empty string, then set element’s name to the empty string.

    5. Otherwise, set element’s name to value.

    6. 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](https://dom.spec.whatwg.org/#element) and [Text](https://dom.spec.whatwg.org/#text) nodes are slottables.

A slot can be a slottable.

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:

  1. If localName is slot and namespace is null, then:

    1. If value is oldValue, then return.

    2. If value is null and oldValue is the empty string, then return.

    3. If value is the empty string and oldValue is null, then return.

    4. If value is null or the empty string, then set element’s name to the empty string.

    5. Otherwise, set element’s name to value.

    6. If element is assigned, then run assign slottables for element’s assigned slot.

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

A slottable has an associated manual slot assignment (null or a slot). Unless stated otherwise, it is null.

A slottable’s manual slot assignment can be implemented using a weak reference to the slot, because this variable is not directly accessible from script.

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:

  1. If slottable’s parent is null, then return null.

  2. Let shadow be slottable’s parent’s shadow root.

  3. If shadow is null, then return null.

  4. If the open flag is set and shadow’s mode is not "open", then return null.

  5. If shadow’s slot assignment is "manual", then return the slot in shadow’s descendants whose manually assigned nodes contains slottable, if any; otherwise null.

  6. Return the first slot in tree order in shadow’s descendants whose name is slottable’s name, if any; otherwise null.

To find slottables for a given slot slot, run these steps:

  1. Let result be an empty list.

  2. Let root be slot’s root.

  3. If root is not a shadow root, then return result.

  4. Let host be root’s host.

  5. If root’s slot assignment is "manual", then:

    1. Let result be « ».

    2. For each slottable slottable of slot’s manually assigned nodes, if slottable’s parent is host, append slottable to result.

  6. Otherwise, for each slottable child slottable of host, in tree order:

    1. Let foundSlot be the result of finding a slot given slottable.

    2. If foundSlot is slot, then append slottable to result.

  7. Return result.

To find flattened slottables for a given slot slot, run these steps:

  1. Let result be an empty list.

  2. If slot’s root is not a shadow root, then return result.

  3. Let slottables be the result of finding slottables given slot.

  4. If slottables is the empty list, then append each slottable child of slot, in tree order, to slottables.

  5. For each node in slottables:

    1. If node is a slot whose root is a shadow root, then:

      1. Let temporaryResult be the result of finding flattened slottables given node.

      2. Append each slottable in temporaryResult, in order, to result.

    2. Otherwise, append node to result.

  6. Return result.

4.2.2.4. Assigning slottables and slots

To assign slottables for a slot slot, run these steps:

  1. Let slottables be the result of finding slottables for slot.

  2. If slottables and slot’s assigned nodes are not identical, then run signal a slot change for slot.

  3. Set slot’s assigned nodes to slottables.

  4. 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:

  1. Let slot be the result of finding a slot with slottable.

  2. 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:

  1. Append slot to slot’s relevant agent’s signal slots.

  2. Queue a mutation observer microtask.

4.2.3. Mutation algorithms

To ensure pre-insertion validity of a node into a parent before a child, run these steps:

  1. If parent is not a [Document](https://dom.spec.whatwg.org/#document), [DocumentFragment](https://dom.spec.whatwg.org/#documentfragment), or [Element](https://dom.spec.whatwg.org/#element) node, then throw a "[HierarchyRequestError](https://webidl.spec.whatwg.org/#hierarchyrequesterror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  2. If node is a host-including inclusive ancestor of parent, then throw a "[HierarchyRequestError](https://webidl.spec.whatwg.org/#hierarchyrequesterror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  3. If child is non-null and its parent is not parent, then throw a "[NotFoundError](https://webidl.spec.whatwg.org/#notfounderror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  4. If node is not a [DocumentFragment](https://dom.spec.whatwg.org/#documentfragment), [DocumentType](https://dom.spec.whatwg.org/#documenttype), [Element](https://dom.spec.whatwg.org/#element), or [CharacterData](https://dom.spec.whatwg.org/#characterdata) node, then throw a "[HierarchyRequestError](https://webidl.spec.whatwg.org/#hierarchyrequesterror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  5. If either node is a [Text](https://dom.spec.whatwg.org/#text) node and parent is a document, or node is a doctype and parent is not a document, then throw a "[HierarchyRequestError](https://webidl.spec.whatwg.org/#hierarchyrequesterror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  6. If parent is a document, and any of the statements below, switched on the interface node implements, are true, then throw a "[HierarchyRequestError](https://webidl.spec.whatwg.org/#hierarchyrequesterror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

    [DocumentFragment](https://dom.spec.whatwg.org/#documentfragment)

    If node has more than one element child or has a [Text](https://dom.spec.whatwg.org/#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](https://dom.spec.whatwg.org/#element)

    parent has an element child, child is a doctype, or child is non-null and a doctype is following child.

    [DocumentType](https://dom.spec.whatwg.org/#documenttype)

    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:

  1. Ensure pre-insertion validity of node into parent before child.

  2. Let referenceChild be child.

  3. If referenceChild is node, then set referenceChild to node’s next sibling.

  4. Insert node into parent before referenceChild.

  5. 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:

  1. Let nodes be node’s children, if node is a [DocumentFragment](https://dom.spec.whatwg.org/#documentfragment) node; otherwise « node ».

  2. Let count be nodes’s size.

  3. If count is 0, then return.

  4. If node is a [DocumentFragment](https://dom.spec.whatwg.org/#documentfragment) node, then:

    1. Remove its children with the suppress observers flag set.

    2. Queue a tree mutation record for node with « », nodes, null, and null.

      This step intentionally does not pay attention to the suppress observers flag.

  5. If child is non-null, then:

    1. For each live range whose start node is parent and start offset is greater than child’s index, increase its start offset by count.

    2. For each live range whose end node is parent and end offset is greater than child’s index, increase its end offset by count.

  6. Let previousSibling be child’s previous sibling or parent’s last child if child is null.

  7. For each node in nodes, in tree order:

    1. Adopt node into parent’s node document.

    2. If child is null, then append node to parent’s children.

    3. Otherwise, insert node into parent’s children before child’s index.

    4. If parent is a shadow host whose shadow root’s slot assignment is "named" and node is a slottable, then assign a slot for node.

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

    6. Run assign slottables for a tree with node’s root.

    7. For each shadow-including inclusive descendant inclusiveDescendant of node, in shadow-including tree order:

      1. Run the insertion steps with inclusiveDescendant.

      2. If inclusiveDescendant is connected, then:

        1. If inclusiveDescendant is custom, then enqueue a custom element callback reaction with inclusiveDescendant, callback name "connectedCallback", and an empty argument list.

        2. Otherwise, try to upgrade inclusiveDescendant.

          If this successfully upgrades inclusiveDescendant, its connectedCallback will be enqueued automatically during the upgrade an element algorithm.

  8. If suppress observers flag is unset, then queue a tree mutation record for parent with nodes, « », previousSibling, and child.

  9. 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:

  1. If parent is not a [Document](https://dom.spec.whatwg.org/#document), [DocumentFragment](https://dom.spec.whatwg.org/#documentfragment), or [Element](https://dom.spec.whatwg.org/#element) node, then throw a "[HierarchyRequestError](https://webidl.spec.whatwg.org/#hierarchyrequesterror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  2. If node is a host-including inclusive ancestor of parent, then throw a "[HierarchyRequestError](https://webidl.spec.whatwg.org/#hierarchyrequesterror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  3. If child’s parent is not parent, then throw a "[NotFoundError](https://webidl.spec.whatwg.org/#notfounderror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  4. If node is not a [DocumentFragment](https://dom.spec.whatwg.org/#documentfragment), [DocumentType](https://dom.spec.whatwg.org/#documenttype), [Element](https://dom.spec.whatwg.org/#element), or [CharacterData](https://dom.spec.whatwg.org/#characterdata) node, then throw a "[HierarchyRequestError](https://webidl.spec.whatwg.org/#hierarchyrequesterror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  5. If either node is a [Text](https://dom.spec.whatwg.org/#text) node and parent is a document, or node is a doctype and parent is not a document, then throw a "[HierarchyRequestError](https://webidl.spec.whatwg.org/#hierarchyrequesterror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  6. If parent is a document, and any of the statements below, switched on the interface node implements, are true, then throw a "[HierarchyRequestError](https://webidl.spec.whatwg.org/#hierarchyrequesterror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

    [DocumentFragment](https://dom.spec.whatwg.org/#documentfragment)

    If node has more than one element child or has a [Text](https://dom.spec.whatwg.org/#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](https://dom.spec.whatwg.org/#element)

    parent has an element child that is not child or a doctype is following child.

    [DocumentType](https://dom.spec.whatwg.org/#documenttype)

    parent has a doctype child that is not child, or an element is preceding child.

    The above statements differ from the pre-insert algorithm.

  7. Let referenceChild be child’s next sibling.

  8. If referenceChild is node, then set referenceChild to node’s next sibling.

  9. Let previousSibling be child’s previous sibling.

  10. Let removedNodes be the empty set.

  11. If child’s parent is non-null, then:

1.  Set removedNodes to « child ».
    
2.  [Remove](https://dom.spec.whatwg.org/#concept-node-remove) child with the _suppress observers flag_ set.
    

The above can only be false if child is node.
  1. Let nodes be node’s children if node is a [DocumentFragment](https://dom.spec.whatwg.org/#documentfragment) node; otherwise « node ».

  2. Insert node into parent before referenceChild with the suppress observers flag set.

  3. Queue a tree mutation record for parent with nodes, removedNodes, previousSibling, and referenceChild.

  4. Return child.

To replace all with a node within a parent, run these steps:

  1. Let removedNodes be parent’s children.

  2. Let addedNodes be the empty set.

  3. If node is a [DocumentFragment](https://dom.spec.whatwg.org/#documentfragment) node, then set addedNodes to node’s children.

  4. Otherwise, if node is non-null, set addedNodes to « node ».

  5. Remove all parent’s children, in tree order, with the suppress observers flag set.

  6. If node is non-null, then insert node into parent before null with the suppress observers flag set.

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

  1. If child’s parent is not parent, then throw a "[NotFoundError](https://webidl.spec.whatwg.org/#notfounderror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  2. Remove child.

  3. 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:

  1. Let parent be node’s parent

  2. Assert: parent is non-null.

  3. Let index be node’s index.

  4. For each live range whose start node is an inclusive descendant of node, set its start to (parent, index).

  5. For each live range whose end node is an inclusive descendant of node, set its end to (parent, index).

  6. For each live range whose start node is parent and start offset is greater than index, decrease its start offset by 1.

  7. For each live range whose end node is parent and end offset is greater than index, decrease its end offset by 1.

  8. For each [NodeIterator](https://dom.spec.whatwg.org/#nodeiterator) object iterator whose root’s node document is node’s node document, run the NodeIterator pre-removing steps given node and iterator.

  9. Let oldPreviousSibling be node’s previous sibling.

  10. Let oldNextSibling be node’s next sibling.

  11. Remove node from its parent’s children.

  12. If node is assigned, then run assign slottables for node’s assigned slot.

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

  14. If node has an inclusive descendant that is a slot, then:

1.  Run [assign slottables for a tree](https://dom.spec.whatwg.org/#assign-slotables-for-a-tree) with parent’s [root](https://dom.spec.whatwg.org/#concept-tree-root).
    
2.  Run [assign slottables for a tree](https://dom.spec.whatwg.org/#assign-slotables-for-a-tree) with node.
  1. Run the removing steps with node and parent.

  2. Let isParentConnected be parent’s connected.

  3. 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](https://dom.spec.whatwg.org/#concept-element-custom) [elements](https://dom.spec.whatwg.org/#concept-element) do not get parent passed. This might change in the future if there is a need.
  1. For each shadow-including descendant descendant of node, in shadow-including tree order, then:
1.  Run the [removing steps](https://dom.spec.whatwg.org/#concept-node-remove-ext) with descendant.
    
2.  If descendant is [custom](https://dom.spec.whatwg.org/#concept-element-custom) and isParentConnected is true, then [enqueue a custom element callback reaction](https://html.spec.whatwg.org/multipage/custom-elements.html#enqueue-a-custom-element-callback-reaction) with descendant, callback name "`disconnectedCallback`", and an empty argument list.
  1. For each inclusive ancestor inclusiveAncestor of parent, and then for each registered of inclusiveAncestor’s registered observer list, if registered’s options["[subtree](https://dom.spec.whatwg.org/#dom-mutationobserverinit-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.

  2. If suppress observers flag is unset, then queue a tree mutation record for parent with « », « node », oldPreviousSibling, and oldNextSibling.

  3. Run the children changed steps for parent.

4.2.4. Mixin [NonElementParentNode](https://dom.spec.whatwg.org/#nonelementparentnode)

Web compatibility prevents the [getElementById()](https://dom.spec.whatwg.org/#dom-nonelementparentnode-getelementbyid) method from being exposed on elements (and therefore on [ParentNode](https://dom.spec.whatwg.org/#parentnode)).

interface mixin NonElementParentNode { Element? getElementById(DOMString elementId); }; Document includes NonElementParentNode; DocumentFragment includes NonElementParentNode;

Document/getElementById

In all current engines.

Firefox1+Safari1+Chrome1+


Opera7+Edge79+


Edge (Legacy)12+IE5.5+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

node . [getElementById](https://dom.spec.whatwg.org/#dom-nonelementparentnode-getelementbyid)(elementId)

Returns the first element within node’s descendants whose ID is elementId.

The getElementById(elementId) method steps are to return the first element, in tree order, within this’s descendants, whose ID is elementId; otherwise, if there is no such element, null.

4.2.5. Mixin [DocumentOrShadowRoot](https://dom.spec.whatwg.org/#documentorshadowroot)

interface mixin DocumentOrShadowRoot { }; Document includes DocumentOrShadowRoot; ShadowRoot includes DocumentOrShadowRoot;

The [DocumentOrShadowRoot](https://dom.spec.whatwg.org/#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](https://dom.spec.whatwg.org/#parentnode)

To convert nodes into a node, given nodes and document, run these steps:

  1. Let node be null.

  2. Replace each string in nodes with a new [Text](https://dom.spec.whatwg.org/#text) node whose data is the string and node document is document.

  3. If nodes contains one node, then set node to nodes[0].

  4. Otherwise, set node to a new [DocumentFragment](https://dom.spec.whatwg.org/#documentfragment) node whose node document is document, and then append each node in nodes, if any, to it.

  5. Return node.

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;

Document/children

In all current engines.

Firefox25+Safari9+Chrome29+


Opera16+Edge79+


Edge (Legacy)16+IENone


Firefox for Android25+iOS Safari9+Chrome for Android29+Android WebView37+Samsung Internet2.0+Opera Mobile16+

DocumentFragment/children

In all current engines.

Firefox25+Safari9+Chrome29+


Opera16+Edge79+


Edge (Legacy)16+IENone


Firefox for Android25+iOS Safari9+Chrome for Android29+Android WebView37+Samsung Internet2.0+Opera Mobile16+

Element/children

In all current engines.

Firefox3.5+Safari4+Chrome1+


Opera10+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari3+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile10.1+

collection = node . `[children](https://dom.spec.whatwg.org/#dom-parentnode-children)`

Returns the child elements.

Document/firstElementChild

In all current engines.

Firefox25+Safari9+Chrome29+


Opera16+Edge79+


Edge (Legacy)17+IENone


Firefox for Android25+iOS Safari9+Chrome for Android29+Android WebView37+Samsung Internet2.0+Opera Mobile16+

DocumentFragment/firstElementChild

In all current engines.

Firefox25+Safari9+Chrome29+


Opera16+Edge79+


Edge (Legacy)17+IENone


Firefox for Android25+iOS Safari9+Chrome for Android29+Android WebView37+Samsung Internet2.0+Opera Mobile16+

Element/firstElementChild

In all current engines.

Firefox3.5+Safari4+Chrome1+


Opera10+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari3+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile10.1+

element = node . `[firstElementChild](https://dom.spec.whatwg.org/#dom-parentnode-firstelementchild)`

Returns the first child that is an element; otherwise null.

Document/lastElementChild

In all current engines.

Firefox25+Safari9+Chrome29+


Opera16+Edge79+


Edge (Legacy)17+IENone


Firefox for Android25+iOS Safari9+Chrome for Android29+Android WebView37+Samsung Internet2.0+Opera Mobile16+

DocumentFragment/lastElementChild

In all current engines.

Firefox25+Safari9+Chrome29+


Opera16+Edge79+


Edge (Legacy)17+IENone


Firefox for Android25+iOS Safari9+Chrome for Android29+Android WebView37+Samsung Internet2.0+Opera Mobile16+

Element/lastElementChild

In all current engines.

Firefox3.5+Safari4+Chrome1+


Opera10+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari3+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile10.1+

element = node . `[lastElementChild](https://dom.spec.whatwg.org/#dom-parentnode-lastelementchild)`

Returns the last child that is an element; otherwise null.

Document/prepend

In all current engines.

Firefox49+Safari10+Chrome54+


Opera41+Edge79+


Edge (Legacy)17+IENone


Firefox for Android49+iOS Safari10+Chrome for Android54+Android WebView54+Samsung Internet6.0+Opera Mobile41+

DocumentFragment/prepend

In all current engines.

Firefox49+Safari10+Chrome54+


Opera41+Edge79+


Edge (Legacy)17+IENone


Firefox for Android49+iOS Safari10+Chrome for Android54+Android WebView54+Samsung Internet6.0+Opera Mobile41+

Element/prepend

In all current engines.

Firefox49+Safari10+Chrome54+


Opera41+Edge79+


Edge (Legacy)17+IENone


Firefox for Android49+iOS Safari10+Chrome for Android54+Android WebView54+Samsung Internet6.0+Opera Mobile41+

node . [prepend](https://dom.spec.whatwg.org/#dom-parentnode-prepend)(nodes)

Inserts nodes before the first child of node, while replacing strings in nodes with equivalent [Text](https://dom.spec.whatwg.org/#text) nodes.

Throws a "[HierarchyRequestError](https://webidl.spec.whatwg.org/#hierarchyrequesterror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException) if the constraints of the node tree are violated.

Document/append

In all current engines.

Firefox49+Safari10+Chrome54+


Opera41+Edge79+


Edge (Legacy)17+IENone


Firefox for Android49+iOS Safari10+Chrome for Android54+Android WebView54+Samsung Internet6.0+Opera Mobile41+

DocumentFragment/append

In all current engines.

Firefox49+Safari10+Chrome54+


Opera41+Edge79+


Edge (Legacy)17+IENone


Firefox for Android49+iOS Safari10+Chrome for Android54+Android WebView54+Samsung Internet6.0+Opera Mobile41+

Element/append

In all current engines.

Firefox49+Safari10+Chrome54+


Opera41+Edge79+


Edge (Legacy)17+IENone


Firefox for Android49+iOS Safari10+Chrome for Android54+Android WebView54+Samsung Internet6.0+Opera Mobile41+

node . [append](https://dom.spec.whatwg.org/#dom-parentnode-append)(nodes)

Inserts nodes after the last child of node, while replacing strings in nodes with equivalent [Text](https://dom.spec.whatwg.org/#text) nodes.

Throws a "[HierarchyRequestError](https://webidl.spec.whatwg.org/#hierarchyrequesterror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException) if the constraints of the node tree are violated.

Document/replaceChildren

In all current engines.

Firefox78+Safari14+Chrome86+


Opera72+Edge86+


Edge (Legacy)NoneIENone


Firefox for Android79+iOS Safari14+Chrome for Android86+Android WebView86+Samsung Internet14.0+Opera Mobile61+

DocumentFragment/replaceChildren

In all current engines.

Firefox78+Safari14+Chrome86+


Opera72+Edge86+


Edge (Legacy)NoneIENone


Firefox for Android79+iOS Safari14+Chrome for Android86+Android WebView86+Samsung Internet14.0+Opera Mobile61+

Element/replaceChildren

In all current engines.

Firefox78+Safari14+Chrome86+


Opera72+Edge86+


Edge (Legacy)NoneIENone


Firefox for Android79+iOS Safari14+Chrome for Android86+Android WebView86+Samsung Internet14.0+Opera Mobile61+

node . [replaceChildren](https://dom.spec.whatwg.org/#dom-parentnode-replacechildren)(nodes)

Replace all children of node with nodes, while replacing strings in nodes with equivalent [Text](https://dom.spec.whatwg.org/#text) nodes.

Throws a "[HierarchyRequestError](https://webidl.spec.whatwg.org/#hierarchyrequesterror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException) if the constraints of the node tree are violated.

Document/querySelector

In all current engines.

Firefox3.5+Safari3.1+Chrome1+


Opera10+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari2+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

DocumentFragment/querySelector

In all current engines.

Firefox3.5+Safari4+Chrome1+


Opera10+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari3+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile10.1+

node . [querySelector](https://dom.spec.whatwg.org/#dom-parentnode-queryselector)(selectors)

Returns the first element that is a descendant of node that matches selectors.

Document/querySelectorAll

In all current engines.

Firefox3.5+Safari3.1+Chrome1+


Opera10+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari2+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

DocumentFragment/querySelectorAll

In all current engines.

Firefox3.5+Safari4+Chrome1+


Opera10+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari3+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile10.1+

Element/querySelector

In all current engines.

Firefox3.5+Safari3.1+Chrome1+


Opera10+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari2+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

Element/querySelectorAll

In all current engines.

Firefox3.5+Safari3.1+Chrome1+


Opera10+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari2+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

node . [querySelectorAll](https://dom.spec.whatwg.org/#dom-parentnode-queryselectorall)(selectors)

Returns all element descendants of node that match selectors.

The children getter steps are to return an [HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection) collection rooted at this matching only element children.

The firstElementChild getter steps are to return the first child that is an element; otherwise null.

The lastElementChild getter steps are to return the last child that is an element; otherwise null.

Document/childElementCount

In all current engines.

Firefox25+Safari9+Chrome29+


Opera16+Edge79+


Edge (Legacy)17+IENone


Firefox for Android25+iOS Safari9+Chrome for Android29+Android WebView37+Samsung Internet2.0+Opera Mobile16+

DocumentFragment/childElementCount

In all current engines.

Firefox25+Safari9+Chrome29+


Opera16+Edge79+


Edge (Legacy)17+IENone


Firefox for Android25+iOS Safari9+Chrome for Android29+Android WebView37+Samsung Internet2.0+Opera Mobile16+

Element/childElementCount

In all current engines.

Firefox3.5+Safari4+Chrome1+


Opera10+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari3+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile10.1+

The childElementCount getter steps are to return the number of children of this that are elements.

The prepend(nodes) method steps are:

  1. Let node be the result of converting nodes into a node given nodes and this’s node document.

  2. Pre-insert node into this before this’s first child.

The append(nodes) method steps are:

  1. Let node be the result of converting nodes into a node given nodes and this’s node document.

  2. Append node to this.

The replaceChildren(nodes) method steps are:

  1. Let node be the result of converting nodes into a node given nodes and this’s node document.

  2. Ensure pre-insertion validity of node into this before null.

  3. Replace all with node within this.

The querySelector(selectors) method steps are to return the first result of running scope-match a selectors string selectors against this, if the result is not an empty list; otherwise null.

The querySelectorAll(selectors) method steps are to return the static result of running scope-match a selectors string selectors against this.

4.2.7. Mixin [NonDocumentTypeChildNode](https://dom.spec.whatwg.org/#nondocumenttypechildnode)

Web compatibility prevents the [previousElementSibling](https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling) and [nextElementSibling](https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling) attributes from being exposed on doctypes (and therefore on [ChildNode](https://dom.spec.whatwg.org/#childnode)).

interface mixin NonDocumentTypeChildNode { readonly attribute Element? previousElementSibling; readonly attribute Element? nextElementSibling; }; Element includes NonDocumentTypeChildNode; CharacterData includes NonDocumentTypeChildNode;

CharacterData/previousElementSibling

In all current engines.

Firefox25+Safari9+Chrome29+


Opera16+Edge79+


Edge (Legacy)17+IENone


Firefox for Android25+iOS Safari9+Chrome for Android29+Android WebView37+Samsung Internet2.0+Opera Mobile16+

Element/previousElementSibling

In all current engines.

Firefox3.5+Safari4+Chrome1+


Opera10+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari3+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile10.1+

element = node . `[previousElementSibling](https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling)`

Returns the first preceding sibling that is an element; otherwise null.

CharacterData/nextElementSibling

In all current engines.

Firefox25+Safari9+Chrome29+


Opera16+Edge79+


Edge (Legacy)17+IENone


Firefox for Android25+iOS Safari9+Chrome for Android29+Android WebView37+Samsung Internet2.0+Opera Mobile16+

Element/nextElementSibling

In all current engines.

Firefox3.5+Safari4+Chrome1+


Opera10+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari3+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile10.1+

element = node . `[nextElementSibling](https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling)`

Returns the first following sibling that is an element; otherwise null.

The previousElementSibling getter steps are to return the first preceding sibling that is an element; otherwise null.

The nextElementSibling getter steps are to return the first following sibling that is an element; otherwise null.

4.2.8. Mixin [ChildNode](https://dom.spec.whatwg.org/#childnode)

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;

CharacterData/before

In all current engines.

Firefox49+Safari10+Chrome54+


Opera39+Edge79+


Edge (Legacy)17+IENone


Firefox for Android49+iOS Safari10+Chrome for Android54+Android WebView54+Samsung Internet6.0+Opera Mobile41+

DocumentType/before

In all current engines.

Firefox49+Safari10+Chrome54+


Opera39+Edge79+


Edge (Legacy)17+IENone


Firefox for Android49+iOS Safari10+Chrome for Android54+Android WebView54+Samsung Internet6.0+Opera Mobile41+

Element/before

In all current engines.

Firefox49+Safari10+Chrome54+


Opera39+Edge79+


Edge (Legacy)17+IENone


Firefox for Android49+iOS Safari10+Chrome for Android54+Android WebView54+Samsung Internet6.0+Opera Mobile41+

node . `[before(...nodes)](https://dom.spec.whatwg.org/#dom-childnode-before)`

Inserts nodes just before node, while replacing strings in nodes with equivalent [Text](https://dom.spec.whatwg.org/#text) nodes.

Throws a "[HierarchyRequestError](https://webidl.spec.whatwg.org/#hierarchyrequesterror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException) if the constraints of the node tree are violated.

CharacterData/after

In all current engines.

Firefox49+Safari10+Chrome54+


Opera39+Edge79+


Edge (Legacy)17+IENone


Firefox for Android49+iOS Safari10+Chrome for Android54+Android WebView54+Samsung Internet6.0+Opera Mobile41+

DocumentType/after

In all current engines.

Firefox49+Safari10+Chrome54+


Opera39+Edge79+


Edge (Legacy)17+IENone


Firefox for Android49+iOS Safari10+Chrome for Android54+Android WebView54+Samsung Internet6.0+Opera Mobile41+

Element/after

In all current engines.

Firefox49+Safari10+Chrome54+


Opera39+Edge79+


Edge (Legacy)17+IENone


Firefox for Android49+iOS Safari10+Chrome for Android54+Android WebView54+Samsung Internet6.0+Opera Mobile41+

node . `[after(...nodes)](https://dom.spec.whatwg.org/#dom-childnode-after)`

Inserts nodes just after node, while replacing strings in nodes with equivalent [Text](https://dom.spec.whatwg.org/#text) nodes.

Throws a "[HierarchyRequestError](https://webidl.spec.whatwg.org/#hierarchyrequesterror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException) if the constraints of the node tree are violated.

CharacterData/replaceWith

In all current engines.

Firefox49+Safari10+Chrome54+


Opera39+Edge79+


Edge (Legacy)17+IENone


Firefox for Android49+iOS Safari10+Chrome for Android54+Android WebView54+Samsung Internet6.0+Opera Mobile41+

DocumentType/replaceWith

In all current engines.

Firefox49+Safari10+Chrome54+


Opera39+Edge79+


Edge (Legacy)17+IENone


Firefox for Android49+iOS Safari10+Chrome for Android54+Android WebView54+Samsung Internet6.0+Opera Mobile41+

Element/replaceWith

In all current engines.

Firefox49+Safari10+Chrome54+


Opera39+Edge79+


Edge (Legacy)17+IENone


Firefox for Android49+iOS Safari10+Chrome for Android54+Android WebView54+Samsung Internet6.0+Opera Mobile41+

node . `[replaceWith(...nodes)](https://dom.spec.whatwg.org/#dom-childnode-replacewith)`

Replaces node with nodes, while replacing strings in nodes with equivalent [Text](https://dom.spec.whatwg.org/#text) nodes.

Throws a "[HierarchyRequestError](https://webidl.spec.whatwg.org/#hierarchyrequesterror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException) if the constraints of the node tree are violated.

CharacterData/remove

In all current engines.

Firefox23+Safari7+Chrome24+


Opera15+Edge79+


Edge (Legacy)12+IENone


Firefox for Android23+iOS Safari7+Chrome for Android25+Android WebView37+Samsung Internet1.5+Opera Mobile14+

DocumentType/remove

In all current engines.

Firefox23+Safari7+Chrome24+


Opera15+Edge79+


Edge (Legacy)12+IENone


Firefox for Android23+iOS Safari7+Chrome for Android25+Android WebView37+Samsung Internet1.5+Opera Mobile14+

Element/remove

In all current engines.

Firefox23+Safari7+Chrome24+


Opera15+Edge79+


Edge (Legacy)12+IENone


Firefox for Android23+iOS Safari7+Chrome for Android25+Android WebView37+Samsung Internet1.5+Opera Mobile14+

node . `[remove()](https://dom.spec.whatwg.org/#dom-childnode-remove)`

Removes node.

The before(nodes) method steps are:

  1. Let parent be this’s parent.

  2. If parent is null, then return.

  3. Let viablePreviousSibling be this’s first preceding sibling not in nodes; otherwise null.

  4. Let node be the result of converting nodes into a node, given nodes and this’s node document.

  5. If viablePreviousSibling is null, then set it to parent’s first child; otherwise to viablePreviousSibling’s next sibling.

  6. Pre-insert node into parent before viablePreviousSibling.

The after(nodes) method steps are:

  1. Let parent be this’s parent.

  2. If parent is null, then return.

  3. Let viableNextSibling be this’s first following sibling not in nodes; otherwise null.

  4. Let node be the result of converting nodes into a node, given nodes and this’s node document.

  5. Pre-insert node into parent before viableNextSibling.

The replaceWith(nodes) method steps are:

  1. Let parent be this’s parent.

  2. If parent is null, then return.

  3. Let viableNextSibling be this’s first following sibling not in nodes; otherwise null.

  4. Let node be the result of converting nodes into a node, given nodes and this’s node document.

  5. If this’s parent is parent, replace this with node within parent.

    This could have been inserted into node.

  6. Otherwise, pre-insert node into parent before viableNextSibling.

The remove() method steps are:

  1. If this’s parent is null, then return.

  2. Remove this.

4.2.9. Mixin [Slottable](https://dom.spec.whatwg.org/#slotable)

interface mixin Slottable { readonly attribute HTMLSlotElement? assignedSlot; }; Element includes Slottable; Text includes Slottable;

Element/assignedSlot

In all current engines.

Firefox63+Safari10.1+Chrome53+


Opera40+Edge79+


Edge (Legacy)NoneIENone


Firefox for Android63+iOS Safari10.3+Chrome for Android53+Android WebView53+Samsung Internet6.0+Opera Mobile41+

Text/assignedSlot

In all current engines.

Firefox63+Safari10.1+Chrome53+


Opera40+Edge79+


Edge (Legacy)18IENone


Firefox for Android63+iOS Safari10.3+Chrome for Android53+Android WebView53+Samsung Internet6.0+Opera Mobile41+

The assignedSlot getter steps are to return the result of find a slot given this and with the open flag set.

4.2.10. Old-style collections: [NodeList](https://dom.spec.whatwg.org/#nodelist) and [HTMLCollection](https://dom.spec.whatwg.org/#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](https://dom.spec.whatwg.org/#nodelist)

NodeList

In all current engines.

Firefox1+Safari1+Chrome1+


Opera8+Edge79+


Edge (Legacy)12+IE5+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

A [NodeList](https://dom.spec.whatwg.org/#nodelist) object is a collection of nodes.

[Exposed=Window] interface NodeList { getter Node? item(unsigned long index); readonly attribute unsigned long length; iterable<Node>; };

NodeList/length

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE5+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

collection . [length](https://dom.spec.whatwg.org/#dom-nodelist-length)

Returns the number of nodes in the collection.

NodeList/item

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE5+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

element = collection . [item(index)](https://dom.spec.whatwg.org/#dom-nodelist-item)

element = collection[index]

Returns the node with index index from the collection. The nodes are sorted in tree order.

4.2.10.2. Interface [HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection)

HTMLCollection

In all current engines.

Firefox1+Safari1+Chrome1+


Opera8+Edge79+


Edge (Legacy)12+IE8+


Firefox for Android4+iOS Safari1+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](https://dom.spec.whatwg.org/#htmlcollection) object is a collection of elements.

[HTMLCollection](https://dom.spec.whatwg.org/#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).

HTMLCollection/length

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE8+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

collection . [length](https://dom.spec.whatwg.org/#dom-htmlcollection-length)

Returns the number of elements in the collection.

HTMLCollection/item

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE8+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

element = collection . [item(index)](https://dom.spec.whatwg.org/#dom-htmlcollection-item)

element = collection[index]

Returns the element with index index from the collection. The elements are sorted in tree order.

element = collection . [namedItem(name)](https://dom.spec.whatwg.org/#dom-htmlcollection-nameditem)

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 getter steps are to return the number of nodes represented by the collection.

The item(index) method steps are to 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:

  1. Let result be an empty list.

  2. For each element represented by the collection, in tree order:

    1. If element has an ID which is not in result, append element’s ID to result.

    2. 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’s name attribute value to result.

  3. Return result.

HTMLCollection/namedItem

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE8+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

The namedItem(key) method steps are:

  1. If key is the empty string, return null.

  2. Return the first element in the collection for which at least one of the following is true:

    or null if there is no such element.

4.3. Mutation observers

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](https://dom.spec.whatwg.org/#mutationobserver) objects), which is initially empty.

To queue a mutation observer microtask, run these steps:

  1. If the surrounding agent’s mutation observer microtask queued is true, then return.

  2. Set the surrounding agent’s mutation observer microtask queued to true.

  3. Queue a microtask to notify mutation observers.

To notify mutation observers, run these steps:

  1. Set the surrounding agent’s mutation observer microtask queued to false.

  2. Let notifySet be a clone of the surrounding agent’s mutation observers.

  3. Let signalSet be a clone of the surrounding agent’s signal slots.

  4. Empty the surrounding agent’s signal slots.

  5. For each mo of notifySet:

    1. Let records be a clone of mo’s record queue.

    2. Empty mo’s record queue.

    3. For each node of mo’s node list, remove all transient registered observers whose observer is mo from node’s registered observer list.

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

  6. For each slot of signalSet, fire an event named [slotchange](https://html.spec.whatwg.org/multipage/indices.html#event-slotchange), with its [bubbles](https://dom.spec.whatwg.org/#dom-event-bubbles) 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](https://dom.spec.whatwg.org/#mutationobserver) object) and options (a [MutationObserverInit](https://dom.spec.whatwg.org/#dictdef-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](https://dom.spec.whatwg.org/#dom-mutationobserverinit-subtree) is set to true on node’s parent.

4.3.1. Interface [MutationObserver](https://dom.spec.whatwg.org/#mutationobserver)

MutationObserver

In all current engines.

Firefox14+Safari7+Chrome26+


Opera15+Edge79+


Edge (Legacy)12+IE11


Firefox for Android14+iOS Safari7+Chrome for Android26+Android WebView37+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](https://dom.spec.whatwg.org/#mutationobserver) object can be used to observe mutations to the tree of nodes.

Each [MutationObserver](https://dom.spec.whatwg.org/#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](https://dom.spec.whatwg.org/#mutationrecord) objects), which is initially empty.

MutationObserver/MutationObserver

In all current engines.

Firefox14+Safari7+Chrome26+


Opera15+Edge79+


Edge (Legacy)12+IE11


Firefox for Android14+iOS Safari7+Chrome for Android26+Android WebView37+Samsung Internet1.5+Opera Mobile14+

observer = new `[MutationObserver(callback)](https://dom.spec.whatwg.org/#dom-mutationobserver-mutationobserver)`

Constructs a [MutationObserver](https://dom.spec.whatwg.org/#mutationobserver) object and sets its callback to callback. The callback is invoked with a list of [MutationRecord](https://dom.spec.whatwg.org/#mutationrecord) objects as first argument and the constructed [MutationObserver](https://dom.spec.whatwg.org/#mutationobserver) object as second argument. It is invoked after nodes registered with the [observe()](https://dom.spec.whatwg.org/#dom-mutationobserver-observe) method, are mutated.

MutationObserver/observe

In all current engines.

Firefox14+Safari6+Chrome18+


Opera15+Edge79+


Edge (Legacy)12+IE11


Firefox for Android14+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

observer . `[observe(target, options)](https://dom.spec.whatwg.org/#dom-mutationobserver-observe)`

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](https://dom.spec.whatwg.org/#dom-mutationobserverinit-childlist)

Set to true if mutations to target’s children are to be observed.

[attributes](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributes)

Set to true if mutations to target’s attributes are to be observed. Can be omitted if [attributeOldValue](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributeoldvalue) or [attributeFilter](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributefilter) is specified.

[characterData](https://dom.spec.whatwg.org/#dom-mutationobserverinit-characterdata)

Set to true if mutations to target’s data are to be observed. Can be omitted if [characterDataOldValue](https://dom.spec.whatwg.org/#dom-mutationobserverinit-characterdataoldvalue) is specified.

[subtree](https://dom.spec.whatwg.org/#dom-mutationobserverinit-subtree)

Set to true if mutations to not just target, but also target’s descendants are to be observed.

[attributeOldValue](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributeoldvalue)

Set to true if [attributes](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributes) is true or omitted and target’s attribute value before the mutation needs to be recorded.

[characterDataOldValue](https://dom.spec.whatwg.org/#dom-mutationobserverinit-characterdataoldvalue)

Set to true if [characterData](https://dom.spec.whatwg.org/#dom-mutationobserverinit-characterdata) is set to true or omitted and target’s data before the mutation needs to be recorded.

[attributeFilter](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributefilter)

Set to a list of attribute local names (without namespace) if not all attribute mutations need to be observed and [attributes](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributes) is true or omitted.

MutationObserver/disconnect

In all current engines.

Firefox14+Safari6+Chrome18+


Opera15+Edge79+


Edge (Legacy)12+IE11


Firefox for Android14+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

observer . `[disconnect()](https://dom.spec.whatwg.org/#dom-mutationobserver-disconnect)`

Stops observer from observing any mutations. Until the [observe()](https://dom.spec.whatwg.org/#dom-mutationobserver-observe) method is used again, observer’s callback will not be invoked.

MutationObserver/takeRecords

In all current engines.

Firefox14+Safari6+Chrome18+


Opera15+Edge79+


Edge (Legacy)12+IE11


Firefox for Android14+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile14+

observer . `[takeRecords()](https://dom.spec.whatwg.org/#dom-mutationobserver-takerecords)`

Empties the record queue and returns what was in there.

The new MutationObserver(callback) constructor steps are:

  1. Set this’s callback to callback.

  2. Append this to this’s relevant agent’s mutation observers.

The observe(target, options) method steps are:

  1. If either options["[attributeOldValue](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributeoldvalue)"] or options["[attributeFilter](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributefilter)"] exists, and options["[attributes](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributes)"] does not exist, then set options["[attributes](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributes)"] to true.

  2. If options["[characterDataOldValue](https://dom.spec.whatwg.org/#dom-mutationobserverinit-characterdataoldvalue)"] exists and options["[characterData](https://dom.spec.whatwg.org/#dom-mutationobserverinit-characterdata)"] does not exist, then set options["[characterData](https://dom.spec.whatwg.org/#dom-mutationobserverinit-characterdata)"] to true.

  3. If none of options["[childList](https://dom.spec.whatwg.org/#dom-mutationobserverinit-childlist)"], options["[attributes](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributes)"], and options["[characterData](https://dom.spec.whatwg.org/#dom-mutationobserverinit-characterdata)"] is true, then throw a TypeError.

  4. If options["[attributeOldValue](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributeoldvalue)"] is true and options["[attributes](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributes)"] is false, then throw a TypeError.

  5. If options["[attributeFilter](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributefilter)"] is present and options["[attributes](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributes)"] is false, then throw a TypeError.

  6. If options["[characterDataOldValue](https://dom.spec.whatwg.org/#dom-mutationobserverinit-characterdataoldvalue)"] is true and options["[characterData](https://dom.spec.whatwg.org/#dom-mutationobserverinit-characterdata)"] is false, then throw a TypeError.

  7. For each registered of target’s registered observer list, if registered’s observer is this:

    1. For each node of this’s node list, remove all transient registered observers whose source is registered from node’s registered observer list.

    2. Set registered’s options to options.

  8. Otherwise:

    1. Append a new registered observer whose observer is this and options is options to target’s registered observer list.

    2. Append target to this’s node list.

The disconnect() method steps are:

  1. For each node of this’s node list, remove any registered observer from node’s registered observer list for which this is the observer.

  2. Empty this’s record queue.

The takeRecords() method steps are:

  1. Let records be a clone of this’s record queue.

  2. Empty this’s record queue.

  3. 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:

  1. Let interestedObservers be an empty map.

  2. Let nodes be the inclusive ancestors of target.

  3. For each node in nodes, and then for each registered of node’s registered observer list:

    1. Let options be registered’s options.

    2. If none of the following are true

      • node is not target and options["[subtree](https://dom.spec.whatwg.org/#dom-mutationobserverinit-subtree)"] is false
      • type is "attributes" and options["[attributes](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributes)"] either does not exist or is false
      • type is "attributes", options["[attributeFilter](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributefilter)"] exists, and options["[attributeFilter](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributefilter)"] does not contain name or namespace is non-null
      • type is "characterData" and options["[characterData](https://dom.spec.whatwg.org/#dom-mutationobserverinit-characterdata)"] either does not exist or is false
      • type is "childList" and options["[childList](https://dom.spec.whatwg.org/#dom-mutationobserverinit-childlist)"] is false

      then:

      1. Let mo be registered’s observer.

      2. If interestedObservers[mo] does not exist, then set interestedObservers[mo] to null.

      3. If either type is "attributes" and options["[attributeOldValue](https://dom.spec.whatwg.org/#dom-mutationobserverinit-attributeoldvalue)"] is true, or type is "characterData" and options["[characterDataOldValue](https://dom.spec.whatwg.org/#dom-mutationobserverinit-characterdataoldvalue)"] is true, then set interestedObservers[mo] to oldValue.

  4. For each observer → mappedOldValue of interestedObservers:

    1. Let record be a new [MutationRecord](https://dom.spec.whatwg.org/#mutationrecord) object with its [type](https://dom.spec.whatwg.org/#dom-mutationrecord-type) set to type, [target](https://dom.spec.whatwg.org/#dom-mutationrecord-target) set to target, [attributeName](https://dom.spec.whatwg.org/#dom-mutationrecord-attributename) set to name, [attributeNamespace](https://dom.spec.whatwg.org/#dom-mutationrecord-attributenamespace) set to namespace, [oldValue](https://dom.spec.whatwg.org/#dom-mutationrecord-oldvalue) set to mappedOldValue, [addedNodes](https://dom.spec.whatwg.org/#dom-mutationrecord-addednodes) set to addedNodes, [removedNodes](https://dom.spec.whatwg.org/#dom-mutationrecord-removednodes) set to removedNodes, [previousSibling](https://dom.spec.whatwg.org/#dom-mutationrecord-previoussibling) set to previousSibling, and [nextSibling](https://dom.spec.whatwg.org/#dom-mutationrecord-nextsibling) set to nextSibling.

    2. Enqueue record to observer’s record queue.

  5. Queue a mutation observer microtask.

To queue a tree mutation record for target with addedNodes, removedNodes, previousSibling, and nextSibling, run these steps:

  1. Assert: either addedNodes or removedNodes is not empty.

  2. Queue a mutation record of "childList" for target with null, null, null, addedNodes, removedNodes, previousSibling, and nextSibling.

4.3.3. Interface [MutationRecord](https://dom.spec.whatwg.org/#mutationrecord)

MutationRecord

In all current engines.

Firefox14+Safari7+Chrome16+


Opera15+Edge79+


Edge (Legacy)12+IE11


Firefox for Android14+iOS Safari7+Chrome for Android25+Android WebView37+Samsung Internet1.5+Opera Mobile14+

[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](https://dom.spec.whatwg.org/#dom-mutationrecord-type)`

Returns "attributes" if it was an attribute mutation. "characterData" if it was a mutation to a [CharacterData](https://dom.spec.whatwg.org/#characterdata) node. And "childList" if it was a mutation to the tree of nodes.

record . `[target](https://dom.spec.whatwg.org/#dom-mutationrecord-target)`

Returns the node the mutation affected, depending on the [type](https://dom.spec.whatwg.org/#dom-mutationrecord-type). For "attributes", it is the element whose attribute changed. For "characterData", it is the [CharacterData](https://dom.spec.whatwg.org/#characterdata) node. For "childList", it is the node whose children changed.

record . `[addedNodes](https://dom.spec.whatwg.org/#dom-mutationrecord-addednodes)`

record . `[removedNodes](https://dom.spec.whatwg.org/#dom-mutationrecord-removednodes)`

Return the nodes added and removed respectively.

record . `[previousSibling](https://dom.spec.whatwg.org/#dom-mutationrecord-previoussibling)`

record . `[nextSibling](https://dom.spec.whatwg.org/#dom-mutationrecord-nextsibling)`

Return the previous and next sibling respectively of the added or removed nodes; otherwise null.

record . `[attributeName](https://dom.spec.whatwg.org/#dom-mutationrecord-attributename)`

Returns the local name of the changed attribute; otherwise null.

record . `[attributeNamespace](https://dom.spec.whatwg.org/#dom-mutationrecord-attributenamespace)`

Returns the namespace of the changed attribute; otherwise null.

record . `[oldValue](https://dom.spec.whatwg.org/#dom-mutationrecord-oldvalue)`

The return value depends on [type](https://dom.spec.whatwg.org/#dom-mutationrecord-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](https://dom.spec.whatwg.org/#node)

Node

In all current engines.

Firefox1+Safari1+Chrome1+


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 ENTITY_REFERENCE_NODE = 5; // legacy const unsigned short ENTITY_NODE = 6; // legacy 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 NOTATION_NODE = 12; // legacy 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? otherNode); // legacy alias of ===

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](https://dom.spec.whatwg.org/#node) is an abstract interface that is used by all nodes. You cannot get a direct instance of it.

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; otherwise node’s parent.

Each node also has a registered observer list.


Node/nodeType

In all current engines.

Firefox1+Safari1.1+Chrome1+


Opera7+Edge79+


Edge (Legacy)12+IE6+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

node . `[nodeType](https://dom.spec.whatwg.org/#dom-node-nodetype)`

Returns a number appropriate for the type of node, as follows:

[Element](https://dom.spec.whatwg.org/#element)

`[Node](https://dom.spec.whatwg.org/#node)` . `[ELEMENT_NODE](https://dom.spec.whatwg.org/#dom-node-element_node)` (1).

[Attr](https://dom.spec.whatwg.org/#attr)

`[Node](https://dom.spec.whatwg.org/#node)` . `[ATTRIBUTE_NODE](https://dom.spec.whatwg.org/#dom-node-attribute_node)` (2).

An exclusive Text node

`[Node](https://dom.spec.whatwg.org/#node)` . `[TEXT_NODE](https://dom.spec.whatwg.org/#dom-node-text_node)` (3).

[CDATASection](https://dom.spec.whatwg.org/#cdatasection)

`[Node](https://dom.spec.whatwg.org/#node)` . `[CDATA_SECTION_NODE](https://dom.spec.whatwg.org/#dom-node-cdata_section_node)` (4).

[ProcessingInstruction](https://dom.spec.whatwg.org/#processinginstruction)

`[Node](https://dom.spec.whatwg.org/#node)` . `[PROCESSING_INSTRUCTION_NODE](https://dom.spec.whatwg.org/#dom-node-processing_instruction_node)` (7).

[Comment](https://dom.spec.whatwg.org/#comment)

`[Node](https://dom.spec.whatwg.org/#node)` . `[COMMENT_NODE](https://dom.spec.whatwg.org/#dom-node-comment_node)` (8).

[Document](https://dom.spec.whatwg.org/#document)

`[Node](https://dom.spec.whatwg.org/#node)` . `[DOCUMENT_NODE](https://dom.spec.whatwg.org/#dom-node-document_node)` (9).

[DocumentType](https://dom.spec.whatwg.org/#documenttype)

`[Node](https://dom.spec.whatwg.org/#node)` . `[DOCUMENT_TYPE_NODE](https://dom.spec.whatwg.org/#dom-node-document_type_node)` (10).

[DocumentFragment](https://dom.spec.whatwg.org/#documentfragment)

`[Node](https://dom.spec.whatwg.org/#node)` . `[DOCUMENT_FRAGMENT_NODE](https://dom.spec.whatwg.org/#dom-node-document_fragment_node)` (11).

Node/nodeName

In all current engines.

Firefox1+Safari7+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE6+


Firefox for Android4+iOS Safari7+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

node . `[nodeName](https://dom.spec.whatwg.org/#dom-node-nodename)`

Returns a string appropriate for the type of node, as follows:

[Element](https://dom.spec.whatwg.org/#element)

Its HTML-uppercased qualified name.

[Attr](https://dom.spec.whatwg.org/#attr)

Its qualified name.

An exclusive Text node

"#text".

[CDATASection](https://dom.spec.whatwg.org/#cdatasection)

"#cdata-section".

[ProcessingInstruction](https://dom.spec.whatwg.org/#processinginstruction)

Its target.

[Comment](https://dom.spec.whatwg.org/#comment)

"#comment".

[Document](https://dom.spec.whatwg.org/#document)

"#document".

[DocumentType](https://dom.spec.whatwg.org/#documenttype)

Its name.

[DocumentFragment](https://dom.spec.whatwg.org/#documentfragment)

"#document-fragment".

The nodeType getter steps are to return the first matching statement, switching on the interface this implements:

[Element](https://dom.spec.whatwg.org/#element)

ELEMENT_NODE (1)

[Attr](https://dom.spec.whatwg.org/#attr)

ATTRIBUTE_NODE (2);

An exclusive Text node

TEXT_NODE (3);

[CDATASection](https://dom.spec.whatwg.org/#cdatasection)

CDATA_SECTION_NODE (4);

[ProcessingInstruction](https://dom.spec.whatwg.org/#processinginstruction)

PROCESSING_INSTRUCTION_NODE (7);

[Comment](https://dom.spec.whatwg.org/#comment)

(8);

[Document](https://dom.spec.whatwg.org/#document)

DOCUMENT_NODE (9);

[DocumentType](https://dom.spec.whatwg.org/#documenttype)

DOCUMENT_TYPE_NODE (10);

[DocumentFragment](https://dom.spec.whatwg.org/#documentfragment)

DOCUMENT_FRAGMENT_NODE (11).

The nodeName getter steps are to return the first matching statement, switching on the interface this implements:

[Element](https://dom.spec.whatwg.org/#element)

Its HTML-uppercased qualified name.

[Attr](https://dom.spec.whatwg.org/#attr)

Its qualified name.

An exclusive Text node

"#text".

[CDATASection](https://dom.spec.whatwg.org/#cdatasection)

"#cdata-section".

[ProcessingInstruction](https://dom.spec.whatwg.org/#processinginstruction)

Its target.

[Comment](https://dom.spec.whatwg.org/#comment)

"#comment".

[Document](https://dom.spec.whatwg.org/#document)

"#document".

[DocumentType](https://dom.spec.whatwg.org/#documenttype)

Its name.

[DocumentFragment](https://dom.spec.whatwg.org/#documentfragment)

"#document-fragment".


Node/baseURI

In all current engines.

Firefox1+Safari7+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IENone


Firefox for Android4+iOS Safari7+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

node . `[baseURI](https://dom.spec.whatwg.org/#dom-node-baseuri)`

Returns node’s node document’s document base URL.

The baseURI getter steps are to return this’s node document’s document base URL, serialized.


Node/isConnected

In all current engines.

Firefox49+Safari10+Chrome51+


Opera38+Edge79+


Edge (Legacy)NoneIENone


Firefox for Android49+iOS Safari10+Chrome for Android51+Android WebView51+Samsung Internet6.0+Opera Mobile41+

node . `[isConnected](https://dom.spec.whatwg.org/#dom-node-isconnected)`

Returns true if node is connected; otherwise false.

Node/ownerDocument

In all current engines.

Firefox9+Safari7+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE6+


Firefox for Android9+iOS Safari7+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

node . `[ownerDocument](https://dom.spec.whatwg.org/#dom-node-ownerdocument)`

Returns the node document. Returns null for documents.

Node/getRootNode

In all current engines.

Firefox53+Safari10.1+Chrome54+


Opera41+Edge79+


Edge (Legacy)NoneIENone


Firefox for Android53+iOS Safari10.3+Chrome for Android54+Android WebView54+Samsung Internet6.0+Opera Mobile41+

node . `[getRootNode()](https://dom.spec.whatwg.org/#dom-node-getrootnode)`

Returns node’s root.

node . [getRootNode](https://dom.spec.whatwg.org/#dom-node-getrootnode)({ composed:true })

Returns node’s shadow-including root.

Node/parentNode

In all current engines.

Firefox1+Safari1.1+Chrome1+


Opera7+Edge79+


Edge (Legacy)12+IE5.5+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

node . `[parentNode](https://dom.spec.whatwg.org/#dom-node-parentnode)`

Returns the parent.

Node/parentElement

In all current engines.

Firefox9+Safari1.1+Chrome1+


Opera7+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android9+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

node . `[parentElement](https://dom.spec.whatwg.org/#dom-node-parentelement)`

Returns the parent element.

Node/hasChildNodes

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE6+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

node . `[hasChildNodes()](https://dom.spec.whatwg.org/#dom-node-haschildnodes)`

Returns whether node has children.

Node/childNodes

In all current engines.

Firefox1+Safari1.2+Chrome1+


Opera7+Edge79+


Edge (Legacy)12+IE5+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

node . `[childNodes](https://dom.spec.whatwg.org/#dom-node-childnodes)`

Returns the children.

Node/firstChild

In all current engines.

Firefox1+Safari7+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE6+


Firefox for Android4+iOS Safari7+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

node . `[firstChild](https://dom.spec.whatwg.org/#dom-node-firstchild)`

Returns the first child.

Node/lastChild

In all current engines.

Firefox1+Safari7+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE6+


Firefox for Android45+iOS Safari7+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

node . `[lastChild](https://dom.spec.whatwg.org/#dom-node-lastchild)`

Returns the last child.

Node/previousSibling

In all current engines.

Firefox1+Safari7+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE5.5+


Firefox for Android4+iOS Safari7+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

node . `[previousSibling](https://dom.spec.whatwg.org/#dom-node-previoussibling)`

Returns the previous sibling.

Node/nextSibling

In all current engines.

Firefox1+Safari1.1+Chrome1+


Opera7+Edge79+


Edge (Legacy)12+IE5.5+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

node . `[nextSibling](https://dom.spec.whatwg.org/#dom-node-nextsibling)`

Returns the next sibling.

The isConnected getter steps are to return true, if this is connected; otherwise false.

The ownerDocument getter steps are to return null, if this is a document; otherwise this’s node document.

The node document of a document is that document itself. All nodes have a node document at all times.

The getRootNode(options) method steps are to return this’s shadow-including root if options["[composed](https://dom.spec.whatwg.org/#dom-getrootnodeoptions-composed)"] is true; otherwise this’s root.

The parentNode getter steps are to return this’s parent.

The parentElement getter steps are to return this’s parent element.

The hasChildNodes() method steps are to return true if this has children; otherwise false.

The childNodes getter steps are to return a [NodeList](https://dom.spec.whatwg.org/#nodelist) rooted at this matching only children.

The firstChild getter steps are to return this’s first child.

The lastChild getter steps are to return this’s last child.

The previousSibling getter steps are to return this’s previous sibling.

The nextSibling getter steps are to return this’s next sibling.


Node/nodeValue

In all current engines.

Firefox1+Safari7+Chrome1+


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 getter steps are to return the following, switching on the interface this implements:

[Attr](https://dom.spec.whatwg.org/#attr)

this’s value.

[CharacterData](https://dom.spec.whatwg.org/#characterdata)

this’s data.

Otherwise

Null.

The [nodeValue](https://dom.spec.whatwg.org/#dom-node-nodevalue) setter steps are to, if the given value is null, act as if it was the empty string instead, and then do as described below, switching on the interface this implements:

[Attr](https://dom.spec.whatwg.org/#attr)

Set an existing attribute value with this and the given value.

[CharacterData](https://dom.spec.whatwg.org/#characterdata)

Replace data with node this, offset 0, count this’s length, and data the given value.

Otherwise

Do nothing.

Node/textContent

In all current engines.

Firefox1+Safari3+Chrome1+


Opera9+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

The textContent getter steps are to return the following, switching on the interface this implements:

[DocumentFragment](https://dom.spec.whatwg.org/#documentfragment)

[Element](https://dom.spec.whatwg.org/#element)

The descendant text content of this.

[Attr](https://dom.spec.whatwg.org/#attr)

this’s value.

[CharacterData](https://dom.spec.whatwg.org/#characterdata)

this’s data.

Otherwise

Null.

To string replace all with a string string within a node parent, run these steps:

  1. Let node be null.

  2. If string is not the empty string, then set node to a new [Text](https://dom.spec.whatwg.org/#text) node whose data is string and node document is parent’s node document.

  3. Replace all with node within parent.

The [textContent](https://dom.spec.whatwg.org/#dom-node-textcontent) setter steps are to, if the given value is null, act as if it was the empty string instead, and then do as described below, switching on the interface this implements:

[DocumentFragment](https://dom.spec.whatwg.org/#documentfragment)

[Element](https://dom.spec.whatwg.org/#element)

String replace all with the given value within this.

[Attr](https://dom.spec.whatwg.org/#attr)

Set an existing attribute value with this and the given value.

[CharacterData](https://dom.spec.whatwg.org/#characterdata)

Replace data with node this, offset 0, count this’s length, and data the given value.

Otherwise

Do nothing.


Node/normalize

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

node . `[normalize()](https://dom.spec.whatwg.org/#dom-node-normalize)`

Removes empty exclusive Text nodes and concatenates the data of remaining contiguous exclusive Text nodes into the first of their nodes.

The normalize() method steps are to run these steps for each descendant exclusive Text node node of this:

  1. Let length be node’s length.

  2. If length is zero, then remove node and continue with the next exclusive Text node, if any.

  3. Let data be the concatenation of the data of node’s contiguous exclusive Text nodes (excluding itself), in tree order.

  4. Replace data with node node, offset length, count 0, and data data.

  5. Let currentNode be node’s next sibling.

  6. While currentNode is an exclusive Text node:

    1. For each live range whose start node is currentNode, add length to its start offset and set its start node to node.

    2. For each live range whose end node is currentNode, add length to its end offset and set its end node to node.

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

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

    5. Add currentNode’s length to length.

    6. Set currentNode to its next sibling.

  7. Remove node’s contiguous exclusive Text nodes (excluding itself), in tree order.


Node/cloneNode

In all current engines.

Firefox1+Safari1.1+Chrome1+


Opera7+Edge79+


Edge (Legacy)12+IE6+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

node . [cloneNode([deep = false])](https://dom.spec.whatwg.org/#dom-node-clonenode)

Returns a copy of node. If deep is true, the copy also includes the node’s descendants.

Node/isEqualNode

In all current engines.

Firefox2+Safari3+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

node . `[isEqualNode(otherNode)](https://dom.spec.whatwg.org/#dom-node-isequalnode)`

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](https://html.spec.whatwg.org/multipage/scripting.html#script) and [input](https://html.spec.whatwg.org/multipage/input.html#the-input-element) elements. SVG ought to do the same for its [script](https://html.spec.whatwg.org/multipage/scripting.html#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:

  1. If document is not given, let document be node’s node document.

  2. If node is an element, then:

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

    2. For each attribute in node’s attribute list:

      1. Let copyAttribute be a clone of attribute.

      2. Append copyAttribute to copy.

  3. Otherwise, let copy be a node that implements the same interfaces as node, and fulfills these additional requirements, switching on the interface node implements:

    [Document](https://dom.spec.whatwg.org/#document)

    Set copy’s encoding, content type, URL, origin, type, and mode to those of node.

    [DocumentType](https://dom.spec.whatwg.org/#documenttype)

    Set copy’s name, public ID, and system ID to those of node.

    [Attr](https://dom.spec.whatwg.org/#attr)

    Set copy’s namespace, namespace prefix, local name, and value to those of node.

    [Text](https://dom.spec.whatwg.org/#text)

    [Comment](https://dom.spec.whatwg.org/#comment)

    Set copy’s data to that of node.

    [ProcessingInstruction](https://dom.spec.whatwg.org/#processinginstruction)

    Set copy’s target and data to those of node.

    Otherwise

    Do nothing.

  4. Set copy’s node document and document to copy, if copy is a document, and set copy’s node document to document otherwise.

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

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

  7. Return copy.

The cloneNode(deep) method steps are:

  1. If this is a shadow root, then throw a "[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  2. 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:

The isEqualNode(otherNode) method steps are to return true if otherNode is non-null and this equals otherNode; otherwise false.

Node/isSameNode

In all current engines.

Firefox48+Safari3+Chrome1+


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 steps are to return true if otherNode is this; otherwise false.


Node/compareDocumentPosition

In all current engines.

Firefox9+Safari4+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android9+iOS Safari3.2+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile12.1+

node . `[compareDocumentPosition(other)](https://dom.spec.whatwg.org/#dom-node-comparedocumentposition)`

Returns a bitmask indicating the position of other relative to node. These are the bits that can be set:

`[Node](https://dom.spec.whatwg.org/#node)` . `[DOCUMENT_POSITION_DISCONNECTED](https://dom.spec.whatwg.org/#dom-node-document_position_disconnected)` (1)

Set when node and other are not in the same tree.

`[Node](https://dom.spec.whatwg.org/#node)` . `[DOCUMENT_POSITION_PRECEDING](https://dom.spec.whatwg.org/#dom-node-document_position_preceding)` (2)

Set when other is preceding node.

`[Node](https://dom.spec.whatwg.org/#node)` . `[DOCUMENT_POSITION_FOLLOWING](https://dom.spec.whatwg.org/#dom-node-document_position_following)` (4)

Set when other is following node.

`[Node](https://dom.spec.whatwg.org/#node)` . `[DOCUMENT_POSITION_CONTAINS](https://dom.spec.whatwg.org/#dom-node-document_position_contains)` (8)

Set when other is an ancestor of node.

`[Node](https://dom.spec.whatwg.org/#node)` . `[DOCUMENT_POSITION_CONTAINED_BY](https://dom.spec.whatwg.org/#dom-node-document_position_contained_by)` (16, 10 in hexadecimal)

Set when other is a descendant of node.

Node/contains

In all current engines.

Firefox9+Safari1.1+Chrome16+


Opera7+Edge79+


Edge (Legacy)12+IENone


Firefox for Android9+iOS Safari1+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile10.1+

node . `[contains(other)](https://dom.spec.whatwg.org/#dom-node-contains)`

Returns true if other is an inclusive descendant of node; otherwise false.

These are the constants [compareDocumentPosition()](https://dom.spec.whatwg.org/#dom-node-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).

The compareDocumentPosition(other) method steps are:

  1. If this is other, then return zero.

  2. Let node1 be other and node2 be this.

  3. Let attr1 and attr2 be null.

  4. If node1 is an attribute, then set attr1 to node1 and node1 to attr1’s element.

  5. If node2 is an attribute, then:

    1. Set attr2 to node2 and node2 to attr2’s element.

    2. If attr1 and node1 are non-null, and node2 is node1, then:

      1. For each attr in node2’s attribute list:

        1. If attr equals attr1, then return the result of adding [DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC](https://dom.spec.whatwg.org/#dom-node-document_position_implementation_specific) and [DOCUMENT_POSITION_PRECEDING](https://dom.spec.whatwg.org/#dom-node-document_position_preceding).

        2. If attr equals attr2, then return the result of adding [DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC](https://dom.spec.whatwg.org/#dom-node-document_position_implementation_specific) and [DOCUMENT_POSITION_FOLLOWING](https://dom.spec.whatwg.org/#dom-node-document_position_following).

  6. If node1 or node2 is null, or node1’s root is not node2’s root, then return the result of adding [DOCUMENT_POSITION_DISCONNECTED](https://dom.spec.whatwg.org/#dom-node-document_position_disconnected), [DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC](https://dom.spec.whatwg.org/#dom-node-document_position_implementation_specific), and either [DOCUMENT_POSITION_PRECEDING](https://dom.spec.whatwg.org/#dom-node-document_position_preceding) or [DOCUMENT_POSITION_FOLLOWING](https://dom.spec.whatwg.org/#dom-node-document_position_following), with the constraint that this is to be consistent, together.

    Whether to return [DOCUMENT_POSITION_PRECEDING](https://dom.spec.whatwg.org/#dom-node-document_position_preceding) or [DOCUMENT_POSITION_FOLLOWING](https://dom.spec.whatwg.org/#dom-node-document_position_following) is typically implemented via pointer comparison. In JavaScript implementations a cached Math.random() value can be used.

  7. 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](https://dom.spec.whatwg.org/#dom-node-document_position_contains) to [DOCUMENT_POSITION_PRECEDING](https://dom.spec.whatwg.org/#dom-node-document_position_preceding).

  8. 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](https://dom.spec.whatwg.org/#dom-node-document_position_contained_by) to [DOCUMENT_POSITION_FOLLOWING](https://dom.spec.whatwg.org/#dom-node-document_position_following).

  9. If node1 is preceding node2, then return [DOCUMENT_POSITION_PRECEDING](https://dom.spec.whatwg.org/#dom-node-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 the same tree.

  10. Return [DOCUMENT_POSITION_FOLLOWING](https://dom.spec.whatwg.org/#dom-node-document_position_following).

The contains(other) method steps are to return true if other is an inclusive descendant of this; otherwise false (including when other is null).


To locate a namespace prefix for an element using namespace, run these steps:

  1. If element’s namespace is namespace and its namespace prefix is non-null, then return its namespace prefix.

  2. If element has an attribute whose namespace prefix is "xmlns" and value is namespace, then return element’s first such attribute’s local name.

  3. If element’s parent element is not null, then return the result of running locate a namespace prefix on that element using namespace.

  4. Return null.

To locate a namespace for a node using prefix, switch on the interface node implements:

[Element](https://dom.spec.whatwg.org/#element)

  1. If its namespace is non-null and its namespace prefix is prefix, then return namespace.

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

  3. If its parent element is null, then return null.

  4. Return the result of running locate a namespace on its parent element using prefix.

[Document](https://dom.spec.whatwg.org/#document)

  1. If its document element is null, then return null.

  2. Return the result of running locate a namespace on its document element using prefix.

[DocumentType](https://dom.spec.whatwg.org/#documenttype)

[DocumentFragment](https://dom.spec.whatwg.org/#documentfragment)

Return null.

[Attr](https://dom.spec.whatwg.org/#attr)

  1. If its element is null, then return null.

  2. Return the result of running locate a namespace on its element using prefix.

Otherwise

  1. If its parent element is null, then return null.

  2. Return the result of running locate a namespace on its parent element using prefix.

Node/lookupPrefix

In all current engines.

Firefox1+Safari3+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

The lookupPrefix(namespace) method steps are:

  1. If namespace is null or the empty string, then return null.

  2. Switch on the interface this implements:

    [Element](https://dom.spec.whatwg.org/#element)

    Return the result of locating a namespace prefix for it using namespace.

    [Document](https://dom.spec.whatwg.org/#document)

    Return the result of locating a namespace prefix for its document element, if its document element is non-null; otherwise null.

    [DocumentType](https://dom.spec.whatwg.org/#documenttype)

    [DocumentFragment](https://dom.spec.whatwg.org/#documentfragment)

    Return null.

    [Attr](https://dom.spec.whatwg.org/#attr)

    Return the result of locating a namespace prefix for its element, if its element is non-null; otherwise null.

    Otherwise

    Return the result of locating a namespace prefix for its parent element, if its parent element is non-null; otherwise null.

Node/lookupNamespaceURI

In all current engines.

Firefox1+Safari3+Chrome1+


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 steps are:

  1. If prefix is the empty string, then set it to null.

  2. Return the result of running locate a namespace for this using prefix.

Node/isDefaultNamespace

In all current engines.

Firefox1+Safari3+Chrome1+


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 steps are:

  1. If namespace is the empty string, then set it to null.

  2. Let defaultNamespace be the result of running locate a namespace for this using null.

  3. Return true if defaultNamespace is the same as namespace; otherwise false.


Node/insertBefore

In all current engines.

Firefox3+Safari1.1+Chrome1+


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 steps are to return the result of pre-inserting node into this before child.

Node/appendChild

In all current engines.

Firefox1+Safari1.1+Chrome1+


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 steps are to return the result of appending node to this.

Node/replaceChild

In all current engines.

Firefox1+Safari1.1+Chrome1+


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 steps are to return the result of replacing child with node within this.

Node/removeChild

In all current engines.

Firefox1+Safari1.1+Chrome1+


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 steps are to return the result of pre-removing child from this.


The list of elements with qualified name qualifiedName for a node root is the [HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection) returned by the following algorithm:

  1. If qualifiedName is U+002A (*), then return a [HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection) rooted at root, whose filter matches only descendant elements.

  2. Otherwise, if root’s node document is an HTML document, return a [HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection) rooted at root, whose filter matches the following descendant elements:

  3. Otherwise, return a [HTMLCollection](https://dom.spec.whatwg.org/#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](https://dom.spec.whatwg.org/#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](https://dom.spec.whatwg.org/#htmlcollection) returned by the following algorithm:

  1. If namespace is the empty string, then set it to null.

  2. If both namespace and localName are U+002A (*), then return a [HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection) rooted at root, whose filter matches descendant elements.

  3. If namespace is U+002A (*), then return a [HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection) rooted at root, whose filter matches descendant elements whose local name is localName.

  4. If localName is U+002A (*), then return a [HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection) rooted at root, whose filter matches descendant elements whose namespace is namespace.

  5. Return a [HTMLCollection](https://dom.spec.whatwg.org/#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](https://dom.spec.whatwg.org/#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](https://dom.spec.whatwg.org/#htmlcollection) returned by the following algorithm:

  1. Let classes be the result of running the ordered set parser on classNames.

  2. If classes is the empty set, return an empty [HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection).

  3. Return a [HTMLCollection](https://dom.spec.whatwg.org/#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"; otherwise in an identical to manner.

When invoked with the same argument, the same [HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection) object may be returned as returned by an earlier call.

4.5. Interface [Document](https://dom.spec.whatwg.org/#document)

Document

In all current engines.

Firefox1+Safari1+Chrome1+


Opera3+Edge79+


Edge (Legacy)12+IE4+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

XMLDocument

In all current engines.

Firefox1+Safari10+Chrome34+


Opera21+Edge79+


Edge (Legacy)12+IENone


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 .characterSet readonly attribute DOMString inputEncoding; // legacy alias of .characterSet readonly 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 ); [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 interface); // legacy

[NewObject] Range createRange();

// NodeFilter.SHOW_ALL = 0xFFFFFFFF [NewObject] NodeIterator createNodeIterator(Node root, optional unsigned long whatToShow = 0xFFFFFFFF, optional NodeFilter? filter = null); [NewObject] TreeWalker createTreeWalker(Node root, optional unsigned long whatToShow = 0xFFFFFFFF, optional NodeFilter? filter = null); };

[Exposed=Window] interface XMLDocument : Document {};

dictionary ElementCreationOptions { DOMString is; };

[Document](https://dom.spec.whatwg.org/#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"; otherwise an HTML document. 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](https://dom.spec.whatwg.org/#dom-event-type) attribute value is "load" or document does not have a browsing context; otherwise the document’s relevant global object.


Document/Document

In all current engines.

Firefox20+Safari8+Chrome60+


Opera47+Edge79+


Edge (Legacy)17+IENone


Firefox for Android20+iOS Safari8+Chrome for Android60+Android WebView60+Samsung Internet8.0+Opera Mobile44+

document = new `[Document()](https://dom.spec.whatwg.org/#dom-document-document)`

Returns a new document.

Document/implementation

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE6+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

document . `[implementation](https://dom.spec.whatwg.org/#dom-document-implementation)`

Returns document’s [DOMImplementation](https://dom.spec.whatwg.org/#domimplementation) object.

Document/URL

In all current engines.

Firefox1+Safari1+Chrome1+


Opera3+Edge79+


Edge (Legacy)12+IE4+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

document . `[URL](https://dom.spec.whatwg.org/#dom-document-url)`

Document/documentURI

In all current engines.

Firefox1+Safari3+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)17+IENone


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

document . `[documentURI](https://dom.spec.whatwg.org/#dom-document-documenturi)`

Returns document’s URL.

Document/compatMode

In all current engines.

Firefox1+Safari3.1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE6+


Firefox for Android4+iOS Safari2+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

document . `[compatMode](https://dom.spec.whatwg.org/#dom-document-compatmode)`

Returns the string "BackCompat" if document’s mode is "quirks"; otherwise "CSS1Compat".

Document/characterSet

In all current engines.

Firefox1+Safari3+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera MobileYes

document . `[characterSet](https://dom.spec.whatwg.org/#dom-document-characterset)`

Returns document’s encoding.

Document/contentType

In all current engines.

Firefox1+Safari9+Chrome36+


Opera23+Edge79+


Edge (Legacy)17+IENone


Firefox for Android4+iOS Safari9+Chrome for Android36+Android WebView37+Samsung Internet3.0+Opera Mobile24+

document . `[contentType](https://dom.spec.whatwg.org/#dom-document-contenttype)`

Returns document’s content type.

The new Document() constructor steps are to set this’s origin to the origin of current global object’s associated Document. [HTML]

Unlike [createDocument()](https://dom.spec.whatwg.org/#dom-domimplementation-createdocument), this constructor does not return an [XMLDocument](https://dom.spec.whatwg.org/#xmldocument) object, but a document ([Document](https://dom.spec.whatwg.org/#document) object).

The implementation getter steps are to return the [DOMImplementation](https://dom.spec.whatwg.org/#domimplementation) object that is associated with this.

The URL and documentURI getter steps are to return this’s URL, serialized.

The compatMode getter steps are to return "BackCompat" if this’s mode is "quirks"; otherwise "CSS1Compat".

The characterSet, charset, and inputEncoding getter steps are to return this’s encoding’s name.

The contentType getter steps are to return this’s content type.


Document/doctype

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE6+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

document . [doctype](https://dom.spec.whatwg.org/#dom-document-doctype)

Returns the doctype or null if there is none.

Document/documentElement

In all current engines.

Firefox1+Safari1+Chrome1+


Opera7+Edge79+


Edge (Legacy)12+IE5+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

document . [documentElement](https://dom.spec.whatwg.org/#dom-document-documentelement)

Returns the document element.

Document/getElementsByTagName

In all current engines.

Firefox1+Safari1+Chrome1+


Opera5.1+Edge79+


Edge (Legacy)12+IE5+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

collection = document . [getElementsByTagName(qualifiedName)](https://dom.spec.whatwg.org/#dom-document-getelementsbytagname)

If qualifiedName is "*" returns a [HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection) of all descendant elements.

Otherwise, returns a [HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection) of all descendant elements whose qualified name is qualifiedName. (Matches case-insensitively against elements in the HTML namespace within an HTML document.)

Document/getElementsByTagNameNS

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

collection = document . [getElementsByTagNameNS(namespace, localName)](https://dom.spec.whatwg.org/#dom-document-getelementsbytagnamens)

If namespace and localName are "*" returns a [HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection) of all descendant elements.

If only namespace is "*" returns a [HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection) of all descendant elements whose local name is localName.

If only localName is "*" returns a [HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection) of all descendant elements whose namespace is namespace.

Otherwise, returns a [HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection) of all descendant elements whose namespace is namespace and local name is localName.

Document/getElementsByClassName

In all current engines.

Firefox3+Safari3.1+Chrome1+


Opera9.5+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari2+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

collection = document . [getElementsByClassName(classNames)](https://dom.spec.whatwg.org/#dom-document-getelementsbyclassname)

Element/getElementsByClassName

In all current engines.

Firefox3+Safari6+Chrome1+


Opera9.5+Edge79+


Edge (Legacy)16+IENone


Firefox for Android4+iOS Safari6+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

collection = element . [getElementsByClassName(classNames)](https://dom.spec.whatwg.org/#dom-element-getelementsbyclassname)

Returns a [HTMLCollection](https://dom.spec.whatwg.org/#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.

The doctype getter steps are to return the child of this that is a doctype; otherwise null.

The documentElement getter steps are to return this’s document element.

The getElementsByTagName(qualifiedName) method steps are to return the list of elements with qualified name qualifiedName for this.

Thus, in an HTML document, document.getElementsByTagName("FOO") 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.

The getElementsByTagNameNS(namespace, localName) method steps are to return the list of elements with namespace namespace and local name localName for this.

The getElementsByClassName(classNames) method steps are to return the list of elements with class names classNames for this.

Given the following XHTML fragment:

<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.getElementById("example").getElementsByClassName("aaa") would return a [HTMLCollection](https://dom.spec.whatwg.org/#htmlcollection) with the two paragraphs p1 and p2 in it.

A call to getElementsByClassName("ccc bbb") would only return one node, however, namely p3. A call to document.getElementById("example").getElementsByClassName("bbb  ccc ") would return the same thing.

A call to getElementsByClassName("aaa,bbb") would return no nodes; none of the elements above are in the aaa,bbb class.


Document/createElement

In all current engines.

Firefox1+Safari1+Chrome1+


Opera6+Edge79+


Edge (Legacy)12+IE5+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

element = document . [createElement(localName [, options])](https://dom.spec.whatwg.org/#dom-document-createelement)

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"; otherwise null.

If localName does not match the [Name](https://www.w3.org/TR/xml/#NT-Name) production an "[InvalidCharacterError](https://webidl.spec.whatwg.org/#invalidcharactererror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException) will be thrown.

When supplied, options’s [is](https://dom.spec.whatwg.org/#dom-elementcreationoptions-is) can be used to create a customized built-in element.

Document/createElementNS

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

element = document . [createElementNS(namespace, qualifiedName [, options])](https://dom.spec.whatwg.org/#dom-document-createelementns)

Returns an element with namespace namespace. Its namespace prefix will be everything before U+003A (:) in qualifiedName or null. Its local name will be everything after U+003A (:) in qualifiedName or qualifiedName.

If qualifiedName does not match the [QName](https://www.w3.org/TR/xml-names/#NT-QName) production an "[InvalidCharacterError](https://webidl.spec.whatwg.org/#invalidcharactererror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException) will be thrown.

If one of the following conditions is true a "[NamespaceError](https://webidl.spec.whatwg.org/#namespaceerror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException) will be thrown:

When supplied, options’s [is](https://dom.spec.whatwg.org/#dom-elementcreationoptions-is) can be used to create a customized built-in element.

Document/createDocumentFragment

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE6+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

documentFragment = document . `[createDocumentFragment()](https://dom.spec.whatwg.org/#dom-document-createdocumentfragment)`

Returns a [DocumentFragment](https://dom.spec.whatwg.org/#documentfragment) node.

Document/createTextNode

In all current engines.

Firefox1+Safari1+Chrome1+


Opera7+Edge79+


Edge (Legacy)12+IE5+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

text = document . `[createTextNode(data)](https://dom.spec.whatwg.org/#dom-document-createtextnode)`

Returns a [Text](https://dom.spec.whatwg.org/#text) node whose data is data.

text = document . `[createCDATASection(data)](https://dom.spec.whatwg.org/#dom-document-createcdatasection)`

Returns a [CDATASection](https://dom.spec.whatwg.org/#cdatasection) node whose data is data.

Document/createCDATASection

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

Document/createComment

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE6+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

comment = document . `[createComment(data)](https://dom.spec.whatwg.org/#dom-document-createcomment)`

Returns a [Comment](https://dom.spec.whatwg.org/#comment) node whose data is data.

Document/createProcessingInstruction

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

processingInstruction = document . `[createProcessingInstruction(target, data)](https://dom.spec.whatwg.org/#dom-document-createprocessinginstruction)`

Returns a [ProcessingInstruction](https://dom.spec.whatwg.org/#processinginstruction) node whose target is target and data is data. If target does not match the [Name](https://www.w3.org/TR/xml/#NT-Name) production an "[InvalidCharacterError](https://webidl.spec.whatwg.org/#invalidcharactererror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException) will be thrown. If data contains "?>" an "[InvalidCharacterError](https://webidl.spec.whatwg.org/#invalidcharactererror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException) will be thrown.

The element interface for any name and namespace is [Element](https://dom.spec.whatwg.org/#element), unless stated otherwise.

The HTML Standard will, e.g., define that for html and the HTML namespace, the [HTMLHtmlElement](https://html.spec.whatwg.org/multipage/semantics.html#htmlhtmlelement) interface is used. [HTML]

The createElement(localName, options) method steps are:

  1. If localName does not match the [Name](https://www.w3.org/TR/xml/#NT-Name) production, then throw an "[InvalidCharacterError](https://webidl.spec.whatwg.org/#invalidcharactererror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  2. If this is an HTML document, then set localName to localName in ASCII lowercase.

  3. Let is be null.

  4. If options is a dictionary and options["[is](https://dom.spec.whatwg.org/#dom-elementcreationoptions-is)"] exists, then set is to it.

  5. Let namespace be the HTML namespace, if this is an HTML document or this’s content type is "application/xhtml+xml"; otherwise null.

  6. 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:

  1. Let namespace, prefix, and localName be the result of passing namespace and qualifiedName to validate and extract.

  2. Let is be null.

  3. If options is a dictionary and options["[is](https://dom.spec.whatwg.org/#dom-elementcreationoptions-is)"] exists, then set is to it.

  4. Return the result of creating an element given document, localName, namespace, prefix, is, and with the synchronous custom elements flag set.

The createElementNS(namespace, qualifiedName, options) method steps are to return the result of running the internal createElementNS steps, given this, namespace, qualifiedName, and options.

[createElement()](https://dom.spec.whatwg.org/#dom-document-createelement) and [createElementNS()](https://dom.spec.whatwg.org/#dom-document-createelementns)'s options parameter is allowed to be a string for web compatibility.

The createDocumentFragment() method steps are to return a new [DocumentFragment](https://dom.spec.whatwg.org/#documentfragment) node whose node document is this.

The createTextNode(data) method steps are to return a new [Text](https://dom.spec.whatwg.org/#text) node whose data is data and node document is this.

No check is performed that data consists of characters that match the [Char](https://www.w3.org/TR/xml/#NT-Char) production.

The createCDATASection(data) method steps are:

  1. If this is an HTML document, then throw a "[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  2. If data contains the string "]]>", then throw an "[InvalidCharacterError](https://webidl.spec.whatwg.org/#invalidcharactererror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  3. Return a new [CDATASection](https://dom.spec.whatwg.org/#cdatasection) node with its data set to data and node document set to this.

The method steps are to return a new [Comment](https://dom.spec.whatwg.org/#comment) node whose data is data and node document is this.

No check is performed that data consists of characters that match the [Char](https://www.w3.org/TR/xml/#NT-Char) production or that it contains two adjacent hyphens or ends with a hyphen.

The createProcessingInstruction(target, data) method steps are:

  1. If target does not match the [Name](https://www.w3.org/TR/xml/#NT-Name) production, then throw an "[InvalidCharacterError](https://webidl.spec.whatwg.org/#invalidcharactererror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).
  2. If data contains the string "?>", then throw an "[InvalidCharacterError](https://webidl.spec.whatwg.org/#invalidcharactererror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).
  3. Return a new [ProcessingInstruction](https://dom.spec.whatwg.org/#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](https://www.w3.org/TR/xml/#NT-Char) production.


Document/importNode

In all current engines.

Firefox1+Safari1+Chrome1+


Opera9+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

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](https://webidl.spec.whatwg.org/#notsupportederror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

Document/adoptNode

In all current engines.

Firefox1+Safari3+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

node = document . [adoptNode(node)](https://dom.spec.whatwg.org/#dom-document-adoptnode)

Moves node from another document and returns it.

If node is a document, throws a "[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException) or, if node is a shadow root, throws a "[HierarchyRequestError](https://webidl.spec.whatwg.org/#hierarchyrequesterror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

The importNode(node, deep) method steps are:

  1. If node is a document or shadow root, then throw a "[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  2. 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:

  1. Let oldDocument be node’s node document.

  2. If node’s parent is non-null, then remove node.

  3. If document is not oldDocument, then:

    1. For each inclusiveDescendant in node’s shadow-including inclusive descendants:

      1. Set inclusiveDescendant’s node document to document.

      2. If inclusiveDescendant is an element, then set the node document of each attribute in inclusiveDescendant’s attribute list to document.

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

    3. For each inclusiveDescendant in node’s shadow-including inclusive descendants, in shadow-including tree order, run the adopting steps with inclusiveDescendant and oldDocument.

The adoptNode(node) method steps are:

  1. If node is a document, then throw a "[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  2. If node is a shadow root, then throw a "[HierarchyRequestError](https://webidl.spec.whatwg.org/#hierarchyrequesterror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  3. If node is a [DocumentFragment](https://dom.spec.whatwg.org/#documentfragment) node whose host is non-null, then return.

  4. Adopt node into this.

  5. Return node.


Document/createAttribute

In all current engines.

Firefox44+Safari1+Chrome1+


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 steps are:

  1. If localName does not match the [Name](https://www.w3.org/TR/xml/#NT-Name) production in XML, then throw an "[InvalidCharacterError](https://webidl.spec.whatwg.org/#invalidcharactererror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  2. If this is an HTML document, then set localName to localName in ASCII lowercase.

  3. Return a new attribute whose local name is localName and node document is this.

The createAttributeNS(namespace, qualifiedName) method steps are:

  1. Let namespace, prefix, and localName be the result of passing namespace and qualifiedName to validate and extract.

  2. Return a new attribute whose namespace is namespace, namespace prefix is prefix, local name is localName, and node document is this.


Document/createEvent

In all current engines.

Firefox1+Safari1+Chrome1+


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 steps are:

  1. Let constructor be null.

  2. 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](https://html.spec.whatwg.org/multipage/browsing-the-web.html#beforeunloadevent)

    [HTML]

    "compositionevent"

    [CompositionEvent](https://www.w3.org/TR/uievents/#compositionevent)

    [UIEVENTS]

    "customevent"

    [CustomEvent](https://dom.spec.whatwg.org/#customevent)

    "devicemotionevent"

    [DeviceMotionEvent](https://w3c.github.io/deviceorientation/spec-source-orientation.html#devicemotion)

    [DEVICE-ORIENTATION]

    "deviceorientationevent"

    [DeviceOrientationEvent](https://w3c.github.io/deviceorientation/spec-source-orientation.html#devicemotion)

    "dragevent"

    [DragEvent](https://html.spec.whatwg.org/multipage/dnd.html#dragevent)

    [HTML]

    "event"

    [Event](https://dom.spec.whatwg.org/#event)

    "events"

    "focusevent"

    [FocusEvent](https://www.w3.org/TR/uievents/#focusevent)

    [UIEVENTS]

    "hashchangeevent"

    [HashChangeEvent](https://html.spec.whatwg.org/multipage/browsing-the-web.html#hashchangeevent)

    [HTML]

    "htmlevents"

    [Event](https://dom.spec.whatwg.org/#event)

    "keyboardevent"

    [KeyboardEvent](https://www.w3.org/TR/uievents/#keyboardevent)

    [UIEVENTS]

    "messageevent"

    [MessageEvent](https://html.spec.whatwg.org/multipage/comms.html#messageevent)

    [HTML]

    "mouseevent"

    [MouseEvent](https://www.w3.org/TR/uievents/#mouseevent)

    [UIEVENTS]

    "mouseevents"

    "storageevent"

    [StorageEvent](https://html.spec.whatwg.org/multipage/webstorage.html#storageevent)

    [HTML]

    "svgevents"

    [Event](https://dom.spec.whatwg.org/#event)

    "textevent"

    [CompositionEvent](https://www.w3.org/TR/uievents/#compositionevent)

    [UIEVENTS]

    "touchevent"

    [TouchEvent](https://w3c.github.io/touch-events/#idl-def-touchevent)

    [TOUCH-EVENTS]

    "uievent"

    [UIEvent](https://www.w3.org/TR/uievents/#uievent)

    [UIEVENTS]

    "uievents"

  3. If constructor is null, then throw a "[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  4. If the interface indicated by constructor is not exposed on the relevant global object of this, then throw a "[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

    Typically user agents disable support for touch events in some configurations, in which case this clause would be triggered for the interface [TouchEvent](https://w3c.github.io/touch-events/#idl-def-touchevent).

  5. Let event be the result of creating an event given constructor.

  6. Initialize event’s [type](https://dom.spec.whatwg.org/#dom-event-type) attribute to the empty string.

  7. Initialize event’s [timeStamp](https://dom.spec.whatwg.org/#dom-event-timestamp) attribute to the result of calling current high resolution time with this’s relevant global object.

  8. Initialize event’s [isTrusted](https://dom.spec.whatwg.org/#dom-event-istrusted) attribute to false.

  9. Unset event’s initialized flag.

  10. Return event.

Event constructors ought to be used instead.


Document/createRange

In all current engines.

Firefox1+Safari1+Chrome1+


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 steps are to return a new live range with (this, 0) as its start an end.

The [Range()](https://dom.spec.whatwg.org/#dom-range-range) constructor can be used instead.


Document/createNodeIterator

In all current engines.

Firefox1+Safari3+Chrome1+


Opera9+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera MobileYes

The createNodeIterator(root, whatToShow, filter) method steps are:

  1. Let iterator be a new [NodeIterator](https://dom.spec.whatwg.org/#nodeiterator) object.

  2. Set iterator’s root and iterator’s reference to root.

  3. Set iterator’s pointer before reference to true.

  4. Set iterator’s whatToShow to whatToShow.

  5. Set iterator’s filter to filter.

  6. Return iterator.

Document/createTreeWalker

In all current engines.

Firefox1+Safari3+Chrome1+


Opera9+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari3+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

The createTreeWalker(root, whatToShow, filter) method steps are:

  1. Let walker be a new [TreeWalker](https://dom.spec.whatwg.org/#treewalker) object.

  2. Set walker’s root and walker’s current to root.

  3. Set walker’s whatToShow to whatToShow.

  4. Set walker’s filter to filter.

  5. Return walker.

4.5.1. Interface [DOMImplementation](https://dom.spec.whatwg.org/#domimplementation)

DOMImplementation

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE6+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

User agents must create a [DOMImplementation](https://dom.spec.whatwg.org/#domimplementation) object whenever a document is created and associate it with that document.

[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 };

DOMImplementation/createDocumentType

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

doctype = document . `[implementation](https://dom.spec.whatwg.org/#dom-document-implementation)` . `[createDocumentType(qualifiedName, publicId, systemId)](https://dom.spec.whatwg.org/#dom-domimplementation-createdocumenttype)`

Returns a doctype, with the given qualifiedName, publicId, and systemId. If qualifiedName does not match the [Name](https://www.w3.org/TR/xml/#NT-Name) production, an "[InvalidCharacterError](https://webidl.spec.whatwg.org/#invalidcharactererror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException) is thrown, and if it does not match the [QName](https://www.w3.org/TR/xml-names/#NT-QName) production, a "[NamespaceError](https://webidl.spec.whatwg.org/#namespaceerror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException) is thrown.

DOMImplementation/createDocument

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

doc = document . `[implementation](https://dom.spec.whatwg.org/#dom-document-implementation)` . [createDocument(namespace, qualifiedName [, doctype = null])](https://dom.spec.whatwg.org/#dom-domimplementation-createdocument)

Returns an [XMLDocument](https://dom.spec.whatwg.org/#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()](https://dom.spec.whatwg.org/#dom-document-createelementns) method, when invoked with namespace and qualifiedName.

DOMImplementation/createHTMLDocument

In all current engines.

Firefox4+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

doc = document . `[implementation](https://dom.spec.whatwg.org/#dom-document-implementation)` . [createHTMLDocument([title])](https://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument)

Returns a document, with a basic tree already constructed including a [title](https://html.spec.whatwg.org/multipage/semantics.html#the-title-element) element, unless the title argument is omitted.

The createDocumentType(qualifiedName, publicId, systemId) method steps are:

  1. Validate qualifiedName.

  2. 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](https://www.w3.org/TR/xml/#NT-PubidChar) production or that systemId does not contain both a '"' and a "'".

The createDocument(namespace, qualifiedName, doctype) method steps are:

  1. Let document be a new [XMLDocument](https://dom.spec.whatwg.org/#xmldocument).

  2. Let element be null.

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

  4. If doctype is non-null, append doctype to document.

  5. If element is non-null, append element to document.

  6. document’s origin is this’s associated document’s origin.

  7. document’s content type is determined by namespace:

    HTML namespace

    application/xhtml+xml

    SVG namespace

    image/svg+xml

    Any other namespace

    application/xml

  8. Return document.

The createHTMLDocument(title) method steps are:

  1. Let doc be a new document that is an HTML document.

  2. Set doc’s content type to "text/html".

  3. Append a new doctype, with "html" as its name and with its node document set to doc, to doc.

  4. Append the result of creating an element given doc, [html](https://html.spec.whatwg.org/multipage/semantics.html#the-html-element), and the HTML namespace, to doc.

  5. Append the result of creating an element given doc, [head](https://html.spec.whatwg.org/multipage/semantics.html#the-head-element), and the HTML namespace, to the [html](https://html.spec.whatwg.org/multipage/semantics.html#the-html-element) element created earlier.

  6. If title is given:

    1. Append the result of creating an element given doc, [title](https://html.spec.whatwg.org/multipage/semantics.html#the-title-element), and the HTML namespace, to the [head](https://html.spec.whatwg.org/multipage/semantics.html#the-head-element) element created earlier.

    2. Append a new [Text](https://dom.spec.whatwg.org/#text) node, with its data set to title (which could be the empty string) and its node document set to doc, to the [title](https://html.spec.whatwg.org/multipage/semantics.html#the-title-element) element created earlier.

  7. Append the result of creating an element given doc, [body](https://html.spec.whatwg.org/multipage/sections.html#the-body-element), and the HTML namespace, to the [html](https://html.spec.whatwg.org/multipage/semantics.html#the-html-element) element created earlier.

  8. doc’s origin is this’s associated document’s origin.

  9. Return doc.

The hasFeature() method steps are to return true.

[hasFeature()](https://dom.spec.whatwg.org/#dom-domimplementation-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](https://dom.spec.whatwg.org/#documenttype)

DocumentType

In all current engines.

Firefox1+Safari3+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

[Exposed=Window] interface DocumentType : Node { readonly attribute DOMString name; readonly attribute DOMString publicId; readonly attribute DOMString systemId; };

[DocumentType](https://dom.spec.whatwg.org/#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 getter steps are to return this’s name.

The publicId getter steps are to return this’s public ID.

The systemId getter steps are to return this’s system ID.

4.7. Interface [DocumentFragment](https://dom.spec.whatwg.org/#documentfragment)

DocumentFragment

In all current engines.

Firefox1+Safari3+Chrome1+


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](https://dom.spec.whatwg.org/#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](https://dom.spec.whatwg.org/#documentfragment) node’s host concept is useful for HTML’s [template](https://html.spec.whatwg.org/multipage/scripting.html#the-template-element) element and for shadow roots, and impacts the pre-insert and replace algorithms.

DocumentFragment/DocumentFragment

In all current engines.

Firefox24+Safari8+Chrome29+


Opera16+Edge79+


Edge (Legacy)17+IENone


Firefox for Android24+iOS Safari8+Chrome for Android29+Android WebView37+Samsung Internet2.0+Opera Mobile16+

tree = new `[DocumentFragment()](https://dom.spec.whatwg.org/#dom-documentfragment-documentfragment)`

Returns a new [DocumentFragment](https://dom.spec.whatwg.org/#documentfragment) node.

The new DocumentFragment() constructor steps are to set this’s node document to current global object’s associated Document.

4.8. Interface [ShadowRoot](https://dom.spec.whatwg.org/#shadowroot)

ShadowRoot

In all current engines.

Firefox63+Safari10.1+Chrome53+


Opera40+Edge79+


Edge (Legacy)NoneIENone


Firefox for Android63+iOS Safari10.3+Chrome for Android53+Android WebView53+Samsung Internet6.0+Opera Mobile41+

[Exposed=Window] interface ShadowRoot : DocumentFragment { readonly attribute ShadowRootMode mode; readonly attribute boolean delegatesFocus; readonly attribute SlotAssignmentMode slotAssignment; readonly attribute Element host; attribute EventHandler onslotchange; };

enum ShadowRootMode { "open", "closed" }; enum SlotAssignmentMode { "manual", "named" };

[ShadowRoot](https://dom.spec.whatwg.org/#shadowroot) nodes are simply known as shadow roots.

Shadow roots have an associated mode ("open" or "closed").

ShadowRoot/delegatesFocus

In all current engines.

Firefox94+Safari15+Chrome53+


Opera40+Edge79+


Edge (Legacy)NoneIENone


Firefox for Android94+iOS Safari15+Chrome for Android53+Android WebView53+Samsung Internet6.0+Opera Mobile41+

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.

Shadow roots have an associated slot assignment ("manual" or "named").

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; otherwise shadow root’s host.

ShadowRoot/mode

In all current engines.

Firefox63+Safari10.1+Chrome53+


Opera40+Edge79+


Edge (Legacy)NoneIENone


Firefox for Android63+iOS Safari10.3+Chrome for Android53+Android WebView53+Samsung Internet6.0+Opera Mobile41+

The mode getter steps are to return this’s mode.

The delegatesFocus getter steps are to return this’s delegates focus.

The slotAssignment getter steps are to return this’s slot assignment.

ShadowRoot/host

In all current engines.

Firefox63+Safari10.1+Chrome53+


Opera40+Edge79+


Edge (Legacy)NoneIENone


Firefox for Android63+iOS Safari10.3+Chrome for Android53+Android WebView53+Samsung Internet6.0+Opera Mobile41+

The host getter steps are to 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](https://html.spec.whatwg.org/multipage/indices.html#event-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; otherwise its root.

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:

To retarget an object A against an object B, repeat these steps until they return an object:

  1. If one of the following is true

    then return A.

  2. Set A to A’s root’s host.

The retargeting algorithm is used by event dispatch as well as other specifications, such as Fullscreen. [FULLSCREEN]

4.9. Interface [Element](https://dom.spec.whatwg.org/#element)

Element

In all current engines.

Firefox1+Safari1+Chrome1+


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 selectors); // legacy alias of .matches

HTMLCollection getElementsByTagName(DOMString qualifiedName); HTMLCollection getElementsByTagNameNS(DOMString? namespace, DOMString localName); HTMLCollection getElementsByClassName(DOMString classNames);

[CEReactions] Element? insertAdjacentElement(DOMString where, Element element); // legacy undefined insertAdjacentText(DOMString where, DOMString data); // legacy };

dictionary ShadowRootInit { required ShadowRootMode mode; boolean delegatesFocus = false; SlotAssignmentMode slotAssignment = "named"; };

[Element](https://dom.spec.whatwg.org/#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; otherwise its namespace prefix, followed by ":", followed by its local name.

An element’s HTML-uppercased qualified name is the return value of these steps:

  1. Let qualifiedName be this’s qualified name.

  2. If this is in the HTML namespace and its node document is an HTML document, then set qualifiedName to qualifiedName in ASCII uppercase.

  3. 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:

  1. If prefix was not given, let prefix be null.

  2. If is was not given, let is be null.

  3. Let result be null.

  4. Let definition be the result of looking up a custom element definition given document, namespace, localName, and is.

  5. 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:

    1. Let interface be the element interface for localName and the HTML namespace.

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

    3. If the synchronous custom elements flag is set, then run this step while catching any exceptions:

      1. Upgrade element using definition.

      If this step threw an exception, then:

      1. Report the exception.

      2. Set result’s custom element state to "failed".

    4. Otherwise, enqueue a custom element upgrade reaction given result and definition.

  6. Otherwise, if definition is non-null, then:

    1. If the synchronous custom elements flag is set, then run these steps while catching any exceptions:

      1. Let C be definition’s constructor.

      2. Set result to the result of constructing C, with no arguments.

      3. Assert: result’s custom element state and custom element definition are initialized.

      4. Assert: result’s namespace is the HTML namespace.

        IDL enforces that result is an [HTMLElement](https://html.spec.whatwg.org/multipage/dom.html#htmlelement) object, which all use the HTML namespace.

      5. If result’s attribute list is not empty, then throw a "[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

      6. If result has children, then throw a "[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

      7. If result’s parent is not null, then throw a "[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

      8. If result’s node document is not document, then throw a "[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

      9. If result’s local name is not equal to localName, then throw a "[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

      10. Set result’s namespace prefix to prefix.

      11. Set result’s is value to null.

      If any of these steps threw an exception, then:

      1. Report the exception.

      2. Set result to a new element that implements the [HTMLUnknownElement](https://html.spec.whatwg.org/multipage/dom.html#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.

    2. Otherwise:

      1. Set result to a new element that implements the [HTMLElement](https://html.spec.whatwg.org/multipage/dom.html#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.

      2. Enqueue a custom element upgrade reaction given result and definition.

  7. Otherwise:

    1. Let interface be the element interface for localName and namespace.

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

    3. 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".

  8. Return result.

Elements also have an attribute list, which is a list exposed through a [NamedNodeMap](https://dom.spec.whatwg.org/#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:

  1. Queue a mutation record of "attributes" for element with attribute’s local name, attribute’s namespace, oldValue, « », « », null, and null.

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

  3. 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:

  1. Handle attribute changes for attribute with attribute’s element, attribute’s value, and value.

  2. Set attribute’s value to value.

To append an attribute attribute to an element element, run these steps:

  1. Handle attribute changes for attribute with element, null, and attribute’s value.

  2. Append attribute to element’s attribute list.

  3. Set attribute’s element to element.

To remove an attribute attribute, run these steps:

  1. Handle attribute changes for attribute with attribute’s element, attribute’s value, and null.

  2. Remove attribute from attribute’s element’s attribute list.

  3. Set attribute’s element to null.

To replace an attribute oldAttr with an attribute newAttr, run these steps:

  1. Handle attribute changes for oldAttr with oldAttr’s element, oldAttr’s value, and newAttr’s value.

  2. Replace oldAttr by newAttr in oldAttr’s element’s attribute list.

  3. Set newAttr’s element to oldAttr’s element.

  4. Set oldAttr’s element to null.


To get an attribute by name given a qualifiedName and element element, run these steps:

  1. If element is in the HTML namespace and its node document is an HTML document, then set qualifiedName to qualifiedName in ASCII lowercase.

  2. Return the first attribute in element’s attribute list whose qualified name is qualifiedName; otherwise null.

To get an attribute by namespace and local name given a namespace, localName, and element element, run these steps:

  1. If namespace is the empty string, then set it to null.

  2. Return the attribute in element’s attribute list whose namespace is namespace and local name is localName, if any; otherwise null.

To get an attribute value given an element element, localName, and optionally a namespace (null unless stated otherwise), run these steps:

  1. Let attr be the result of getting an attribute given namespace, localName, and element.

  2. If attr is null, then return the empty string.

  3. Return attr’s value.

To set an attribute given an attr and element, run these steps:

  1. If attr’s element is neither null nor element, throw an "[InUseAttributeError](https://webidl.spec.whatwg.org/#inuseattributeerror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  2. Let oldAttr be the result of getting an attribute given attr’s namespace, attr’s local name, and element.

  3. If oldAttr is attr, return attr.

  4. If oldAttr is non-null, then replace oldAttr with attr.

  5. Otherwise, append attr to element.

  6. 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:

  1. If prefix is not given, set it to null.
  2. If namespace is not given, set it to null.
  3. Let attribute be the result of getting an attribute given namespace, localName, and element.
  4. 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.
  5. Change attribute to value.

To remove an attribute by name given a qualifiedName and element element, run these steps:

  1. Let attr be the result of getting an attribute given qualifiedName and element.

  2. If attr is non-null, then remove attr.

  3. Return attr.

To remove an attribute by namespace and local name given a namespace, localName, and element element, run these steps:

  1. Let attr be the result of getting an attribute given namespace, localName, and element.

  2. If attr is non-null, then remove attr.

  3. 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:

  1. If localName is id, namespace is null, and value is null or the empty string, then unset element’s ID.

  2. 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](https://dom.spec.whatwg.org/#element) is known as its parent element. If the node has a parent of a different type, its parent element is null.


Element/namespaceURI

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

namespace = element . [namespaceURI](https://dom.spec.whatwg.org/#dom-element-namespaceuri)

Returns the namespace.

Element/prefix

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

prefix = element . [prefix](https://dom.spec.whatwg.org/#dom-element-prefix)

Returns the namespace prefix.

Element/localName

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

localName = element . [localName](https://dom.spec.whatwg.org/#dom-element-localname)

Returns the local name.

Element/tagName

In all current engines.

Firefox1+Safari1+Chrome1+


Opera8+Edge79+


Edge (Legacy)12+IE5+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

qualifiedName = element . [tagName](https://dom.spec.whatwg.org/#dom-element-tagname)

Returns the HTML-uppercased qualified name.

The namespaceURI getter steps are to return this’s namespace.

The prefix getter steps are to return this’s namespace prefix.

The localName getter steps are to return this’s local name.

The tagName getter steps are to return this’s HTML-uppercased qualified name.


Element/id

In all current engines.

Firefox1+Safari1+Chrome23+


Opera12.1+Edge79+


Edge (Legacy)12+IE5+


Firefox for Android4+iOS Safari1+Chrome for Android25+Android WebView37+Samsung Internet1.5+Opera Mobile12.1+

element . [id](https://dom.spec.whatwg.org/#dom-element-id) [ = value ]

Returns the value of element’s id content attribute. Can be set to change it.

Element/className

In all current engines.

Firefox1+Safari1+Chrome22+


Opera8+Edge79+


Edge (Legacy)12+IE5+


Firefox for Android4+iOS Safari1+Chrome for Android25+Android WebView37+Samsung Internet1.5+Opera Mobile10.1+

element . [className](https://dom.spec.whatwg.org/#dom-element-classname) [ = value ]

Returns the value of element’s class content attribute. Can be set to change it.

Element/classList

In all current engines.

Firefox3.6+Safari7+Chrome22+


Opera11.5+Edge79+


Edge (Legacy)16+IENone


Firefox for Android4+iOS Safari7+Chrome for Android25+Android WebView4.4+Samsung Internet1.5+Opera Mobile11.5+

element . [classList](https://dom.spec.whatwg.org/#dom-element-classlist)

Allows for manipulation of element’s class content attribute as a set of whitespace-separated tokens through a [DOMTokenList](https://dom.spec.whatwg.org/#domtokenlist) object.

Element/slot

In all current engines.

Firefox63+Safari10+Chrome53+


Opera40+Edge79+


Edge (Legacy)NoneIENone


Firefox for Android63+iOS Safari10+Chrome for Android53+Android WebView53+Samsung Internet6.0+Opera Mobile41+

Global_attributes/slot

In all current engines.

Firefox63+Safari10+Chrome53+


Opera40+Edge79+


Edge (Legacy)NoneIE?


Firefox for Android63+iOS Safari10+Chrome for Android53+Android WebView53+Samsung Internet6.0+Opera Mobile41+

element . [slot](https://dom.spec.whatwg.org/#dom-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.

The id attribute must reflect the "id" content attribute.

The className attribute must reflect the "class" content attribute.

The classList getter steps are to return a [DOMTokenList](https://dom.spec.whatwg.org/#domtokenlist) object whose associated element is this and whose associated attribute’s local name is class. The token set of this particular [DOMTokenList](https://dom.spec.whatwg.org/#domtokenlist) object are also known as the element’s classes.

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

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE8+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

element . [hasAttributes](https://dom.spec.whatwg.org/#dom-element-hasattributes)()

Returns true if element has attributes; otherwise false.

Element/getAttributeNames

In all current engines.

Firefox45+Safari10.1+Chrome61+


Opera48+Edge79+


Edge (Legacy)18IENone


Firefox for Android45+iOS Safari10.3+Chrome for Android61+Android WebView61+Samsung Internet8.0+Opera Mobile45+

element . [getAttributeNames](https://dom.spec.whatwg.org/#dom-element-getattributenames)()

Returns the qualified names of all element’s attributes. Can contain duplicates.

Element/getAttribute

In all current engines.

Firefox1+Safari1+Chrome1+


Opera8+Edge79+


Edge (Legacy)12+IE5+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

element . [getAttribute](https://dom.spec.whatwg.org/#dom-element-getattribute)(qualifiedName)

Returns element’s first attribute whose qualified name is qualifiedName, and null if there is no such attribute otherwise.

[Element/getAttributeNS](https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttributeNS "The getAttributeNS() method of the Element interface returns the string value of the attribute with the specified namespace and name. If the named attribute does not exist, the value returned will either be null or "" (the empty string); see Notes for details.")

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

element . [getAttributeNS](https://dom.spec.whatwg.org/#dom-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

In all current engines.

Firefox1+Safari1+Chrome1+


Opera8+Edge79+


Edge (Legacy)12+IE5+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

element . [setAttribute](https://dom.spec.whatwg.org/#dom-element-setattribute)(qualifiedName, value)

Sets the value of element’s first attribute whose qualified name is qualifiedName to value.

Element/setAttributeNS

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

element . [setAttributeNS](https://dom.spec.whatwg.org/#dom-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

In all current engines.

Firefox1+Safari1+Chrome1+


Opera8+Edge79+


Edge (Legacy)12+IE5+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

element . [removeAttribute](https://dom.spec.whatwg.org/#dom-element-removeattribute)(qualifiedName)

Removes element’s first attribute whose qualified name is qualifiedName.

Element/removeAttributeNS

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

element . [removeAttributeNS](https://dom.spec.whatwg.org/#dom-element-removeattributens)(namespace, localName)

Removes element’s attribute whose namespace is namespace and local name is localName.

Element/toggleAttribute

In all current engines.

Firefox63+Safari12+Chrome69+


Opera56+Edge79+


Edge (Legacy)18IENone


Firefox for Android63+iOS Safari12+Chrome for Android69+Android WebView69+Samsung Internet10.0+Opera Mobile48+

element . [toggleAttribute](https://dom.spec.whatwg.org/#dom-element-toggleattribute)(qualifiedName [, force])

If force is not given, "toggles" qualifiedName, removing it if it is present and adding it if it is not present. If force is true, adds qualifiedName. If force is false, removes qualifiedName.

Returns true if qualifiedName is now present; otherwise false.

Element/hasAttribute

In all current engines.

Firefox1+Safari1+Chrome1+


Opera8+Edge79+


Edge (Legacy)12+IE8+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

element . [hasAttribute](https://dom.spec.whatwg.org/#dom-element-hasattribute)(qualifiedName)

Returns true if element has an attribute whose qualified name is qualifiedName; otherwise false.

Element/hasAttributeNS

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

element . [hasAttributeNS](https://dom.spec.whatwg.org/#dom-element-hasattributens)(namespace, localName)

Returns true if element has an attribute whose namespace is namespace and local name is localName.

The hasAttributes() method steps are to return false if this’s attribute list is empty; otherwise true.

Element/attributes

In all current engines.

Firefox1+Safari1+Chrome1+


Opera8+Edge79+


Edge (Legacy)12+IE5.5+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

The attributes getter steps are to return the associated [NamedNodeMap](https://dom.spec.whatwg.org/#namednodemap).

The getAttributeNames() method steps are to return the qualified names of the attributes in this’s attribute list, in order; otherwise a new list.

These are not guaranteed to be unique.

The getAttribute(qualifiedName) method steps are:

  1. Let attr be the result of getting an attribute given qualifiedName and this.

  2. If attr is null, return null.

  3. Return attr’s value.

The getAttributeNS(namespace, localName) method steps are:

  1. Let attr be the result of getting an attribute given namespace, localName, and this.

  2. If attr is null, return null.

  3. Return attr’s value.

The setAttribute(qualifiedName, value) method steps are:

  1. If qualifiedName does not match the [Name](https://www.w3.org/TR/xml/#NT-Name) production in XML, then throw an "[InvalidCharacterError](https://webidl.spec.whatwg.org/#invalidcharactererror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  2. If this is in the HTML namespace and its node document is an HTML document, then set qualifiedName to qualifiedName in ASCII lowercase.

  3. Let attribute be the first attribute in this’s attribute list whose qualified name is qualifiedName, and null otherwise.

  4. If attribute is null, create an attribute whose local name is qualifiedName, value is value, and node document is this’s node document, then append this attribute to this, and then return.

  5. Change attribute to value.

The setAttributeNS(namespace, qualifiedName, value) method steps are:

  1. Let namespace, prefix, and localName be the result of passing namespace and qualifiedName to validate and extract.

  2. Set an attribute value for this using localName, value, and also prefix and namespace.

The removeAttribute(qualifiedName) method steps are to remove an attribute given qualifiedName and this, and then return undefined.

The removeAttributeNS(namespace, localName) method steps are to remove an attribute given namespace, localName, and this, and then return undefined.

The hasAttribute(qualifiedName) method steps are:

  1. If this is in the HTML namespace and its node document is an HTML document, then set qualifiedName to qualifiedName in ASCII lowercase.

  2. Return true if this has an attribute whose qualified name is qualifiedName; otherwise false.

The toggleAttribute(qualifiedName, force) method steps are:

  1. If qualifiedName does not match the [Name](https://www.w3.org/TR/xml/#NT-Name) production in XML, then throw an "[InvalidCharacterError](https://webidl.spec.whatwg.org/#invalidcharactererror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  2. If this is in the HTML namespace and its node document is an HTML document, then set qualifiedName to qualifiedName in ASCII lowercase.

  3. Let attribute be the first attribute in this’s attribute list whose qualified name is qualifiedName, and null otherwise.

  4. If attribute is null, then:

    1. If force is not given or is true, create an attribute whose local name is qualifiedName, value is the empty string, and node document is this’s node document, then append this attribute to this, and then return true.

    2. Return false.

  5. Otherwise, if force is not given or is false, remove an attribute given qualifiedName and this, and then return false.

  6. Return true.

The hasAttributeNS(namespace, localName) method steps are:

  1. If namespace is the empty string, then set it to null.

  2. Return true if this has an attribute whose namespace is namespace and local name is localName; otherwise false.


Element/getAttributeNode

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE6+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

The getAttributeNode(qualifiedName) method steps are to return the result of getting an attribute given qualifiedName and this.

Element/getAttributeNodeNS

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

The getAttributeNodeNS(namespace, localName) method steps are to return the result of getting an attribute given namespace, localName, and this.

Element/setAttributeNode

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE6+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

Element/setAttributeNodeNS

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE9+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

The setAttributeNode(attr) and setAttributeNodeNS(attr) methods steps are to return the result of setting an attribute given attr and this.

Element/removeAttributeNode

In all current engines.

Firefox1+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE6+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

The removeAttributeNode(attr) method steps are:

  1. If this’s attribute list does not contain attr, then throw a "[NotFoundError](https://webidl.spec.whatwg.org/#notfounderror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  2. Remove attr.

  3. Return attr.


Element/attachShadow

In all current engines.

Firefox63+Safari10+Chrome53+


Opera40+Edge79+


Edge (Legacy)NoneIENone


Firefox for Android63+iOS Safari10+Chrome for Android53+Android WebView53+Samsung Internet6.0+Opera Mobile41+

var shadow = element . `[attachShadow(init)](https://dom.spec.whatwg.org/#dom-element-attachshadow)`

Creates a shadow root for element and returns it.

Element/shadowRoot

In all current engines.

Firefox63+Safari10+Chrome35+


Opera22+Edge79+


Edge (Legacy)NoneIENone


Firefox for Android63+iOS Safari10+Chrome for Android35+Android WebView37+Samsung Internet3.0+Opera Mobile22+

var shadow = element . `[shadowRoot](https://dom.spec.whatwg.org/#dom-element-shadowroot)`

Returns element’s shadow root, if any, and if shadow root’s mode is "open", and null otherwise.

The attachShadow(init) method steps are:

  1. If this’s namespace is not the HTML namespace, then throw a "[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  2. If this’s local name is not one of the following:

    • a valid custom element name
    • "article", "aside", "blockquote", "body", "div", "footer", "h1", "h2", "h3", "h4", "h5", "h6", "header", "main", "nav", "p", "section", or "span"

    then throw a "[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  3. If this’s local name is a valid custom element name, or this’s is value is not null, then:

    1. Let definition be the result of looking up a custom element definition given this’s node document, its namespace, its local name, and its is value.

    2. If definition is not null and definition’s disable shadow is true, then throw a "[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  4. If this is a shadow host, then throw an "[NotSupportedError](https://webidl.spec.whatwg.org/#notsupportederror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  5. Let shadow be a new shadow root whose node document is this’s node document, host is this, and mode is init["[mode](https://dom.spec.whatwg.org/#dom-shadowrootinit-mode)"].

  6. Set shadow’s delegates focus to init["[delegatesFocus](https://dom.spec.whatwg.org/#dom-shadowrootinit-delegatesfocus)"].

  7. If this’s custom element state is "precustomized" or "custom", then set shadow’s available to element internals to true.

  8. Set shadow’s slot assignment to init["[slotAssignment](https://dom.spec.whatwg.org/#dom-shadowrootinit-slotassignment)"].

  9. Set this’s shadow root to shadow.

  10. Return shadow.

The shadowRoot getter steps are:

  1. Let shadow be this’s shadow root.

  2. If shadow is null or its mode is "closed", then return null.

  3. Return shadow.


Element/closest

In all current engines.

Firefox35+Safari6+Chrome41+


Opera28+Edge79+


Edge (Legacy)15+IENone


Firefox for Android35+iOS Safari9+Chrome for Android41+Android WebView41+Samsung Internet4.0+Opera Mobile28+

element . `[closest(selectors)](https://dom.spec.whatwg.org/#dom-element-closest)`

Returns the first (starting at element) inclusive ancestor that matches selectors, and null otherwise.

[Element/matches](https://developer.mozilla.org/en-US/docs/Web/API/Element/matches "The matches() method checks to see if the Element would be selected by the provided selectorString -- in other words -- checks if the element "is" the selector.")

In all current engines.

Firefox34+Safari7+Chrome33+


Opera21+Edge79+


Edge (Legacy)15+IENone


Firefox for Android34+iOS Safari8+Chrome for Android33+Android WebView4.4+Samsung Internet2.0+Opera Mobile21+

element . `[matches(selectors)](https://dom.spec.whatwg.org/#dom-element-matches)`

Returns true if matching selectors against element’s root yields element; otherwise false.

The closest(selectors) method steps are:

  1. Let s be the result of parse a selector from selectors. [SELECTORS4]
  2. If s is failure, throw a "[SyntaxError](https://webidl.spec.whatwg.org/#syntaxerror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).
  3. Let elements be this’s inclusive ancestors that are elements, in reverse tree order.
  4. For each element in elements, if match a selector against an element, using s, element, and :scope element this, returns success, return element. [SELECTORS4]
  5. Return null.

The matches(selectors) and webkitMatchesSelector(selectors) method steps are:

  1. Let s be the result of parse a selector from selectors. [SELECTORS4]

  2. If s is failure, then throw a "[SyntaxError](https://webidl.spec.whatwg.org/#syntaxerror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

  3. If the result of match a selector against an element, using s, this, and :scope element this, returns success, then return true; otherwise, return false. [SELECTORS4]


Element/getElementsByTagName

In all current engines.

Firefox1+Safari1+Chrome1+


Opera8+Edge79+


Edge (Legacy)12+IE5.5+


Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

The getElementsByTagName(qualifiedName) method steps are to return the list of elements with qualified name qualifiedName for this.

Element/getElementsByTagNameNS

In all current engines.

Firefox1+Safari1+Chrome1+


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 steps are to return the list of elements with namespace namespace and local name localName for this.

The getElementsByClassName(classNames) method steps are to return the list of elements with class names classNames for this.


To insert adjacent, given an element element, string where, and a node node, run the steps associated with the first ASCII case-insensitive match for where:

"beforebegin"

If element’s parent is null, return null.

Return the result of pre-inserting node into element’s parent before element.

"afterbegin"

Return the result of pre-inserting node into element before element’s first child.

"beforeend"

Return the result of pre-inserting node into element before null.

"afterend"

If element’s parent is null, return null.

Return the result of pre-inserting node into element’s parent before element’s next sibling.

Otherwise

Throw a "[SyntaxError](https://webidl.spec.whatwg.org/#syntaxerror)" [DOMException](https://webidl.spec.whatwg.org/#idl-DOMException).

Element/insertAdjacentElement

In all current engines.

Firefox48+Safari3+Chrome1+


Opera8+Edge79+


Edge (Legacy)17+IENone


Firefox for Android48+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+

The insertAdjacentElement(where, element) method steps are to return the result of running insert adjacent, give this, where, and element.

Element/insertAdjacentText

In all current engines.

Firefox48+Safari4+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)17+IENone


Firefox for Android48+iOS Safari4+Chrome for Android18+Android WebView2.2+Samsung Internet1.0+Opera Mobile12.1+

The insertAdjacentText(where, data) method steps are:

  1. Let text be a new [Text](https://dom.spec.whatwg.org/#text) node whose data is data and node document is this’s node document.

  2. Run insert adjacent, given this, where, and text.

This method returns nothing because it existed before we had a chance to design it.

4.9.1. Interface [NamedNodeMap](https://dom.spec.whatwg.org/#namednodemap)

NamedNodeMap

In all current engines.

Firefox34+Safari1+Chrome1+


Opera12.1+Edge79+


Edge (Legacy)12+IE5+


Firefox for Android34+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile12.1+

[Exposed=Window, LegacyUnenumerableNamedProperties] interface NamedNodeMap { readonly attribute unsigned long length; getter Attr? item(unsigned long index); getter Attr? getNamedItem(DOMString qualifiedName); Attr? getNamedItemNS(DOMString? namespace, DOMString localName); [CEReactions] Attr? setNamedItem(Attr attr); [CEReactions] Attr? setNamedItemNS(Attr attr); [CEReactions] Attr removeNamedItem(DOMString qualifiedName); [CEReactions] Attr removeNamedItemNS([DOMString](https://webidl.spec.whatw

Sitemap:


Wiki Navigation

Sitemap:

- [✅] HOME

- [✅] admin

- [✅] blog

- [✅] docs

- [✅] readme

- [✅] showcase

- [✅] blog/hoisting

- [✅] docs/about

- [✅] docs/articles

- [✅] docs/audio

- [✅] docs/career

- [✅] docs/content

- [✅] docs/css

- [✅] docs/docs

- [✅] docs/ds-algo

- [✅] docs/faq

- [✅] docs/git

- [✅] docs/interact

- [✅] docs/js-tips

- [✅] docs/leetcode

- [✅] docs/overflow

- [✅] docs/projects

- [✅] docs/python

- [✅] docs/react

- [✅] docs/sitemap

- [✅] docs/tips

- [✅] docs/tools

- [✅] docs/docs/css

Clone this wiki locally