OscillatorNode: type property - Web APIs

OscillatorNode: type property
=============================

 The **`type`** property of the `OscillatorNode` interface specifies what shape of waveform the
 oscillator will output. There are several common waveforms available, as well as an
 option to specify a custom waveform shape. The shape of the waveform will affect the
 tone that is produced.

Value
-----

 A string specifying the shape of oscillator wave. The different
 available values are:

`sine`

A sine wave. This is the default value.

`square`

A square wave with a duty cycle of 0.5; that is, the signal is "high" for half of each period.

`sawtooth`

A sawtooth wave.

`triangle`

A triangle wave.

`custom`

 A custom waveform. You never set `type` to `custom` manually;
 instead, use the `setPeriodicWave()`
 method to provide the data representing the waveform. Doing so automatically sets the
 `type` to `custom`.

### Exceptions

`InvalidStateError` `DOMException`

 Thrown if the value `custom` was specified. To set a custom waveform, just call
 `setPeriodicWave()`. Doing so
 automatically sets the type for you.

Examples
--------

 The following example shows basic usage of an `AudioContext` to create
 an oscillator node. For an applied example, check out our Violent Theremin demo (see app.js for relevant code).

```js
// create web audio api context
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();

// create Oscillator node
const oscillator = audioCtx.createOscillator();

oscillator.type = "square";
oscillator.frequency.setValueAtTime(440, audioCtx.currentTime); // value in hertz
oscillator.start();
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-oscillatornode-type |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API


OscillatorNode: detune property - Web APIs

OscillatorNode: detune property
===============================

The `detune` property of the `OscillatorNode` interface is an a-rate `AudioParam` representing detuning of oscillation in cents.

**Note:** though the `AudioParam` returned is read-only, the value it represents is not.

Value
-----

An a-rate `AudioParam`.

Examples
--------

The following example shows basic usage of an `AudioContext` to create an oscillator node. For applied examples/information, check out our Violent Theremin demo (see app.js for relevant code).

```js
// create web audio api context
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();

// create Oscillator node
const oscillator = audioCtx.createOscillator();

oscillator.type = "square";
oscillator.frequency.setValueAtTime(440, audioCtx.currentTime); // value in hertz
oscillator.detune.setValueAtTime(100, audioCtx.currentTime); // value in cents
oscillator.start();
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-oscillatornode-detune |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API


DOMParser: DOMParser() constructor - Web APIs

DOMParser: DOMParser() constructor
==================================

The **`DOMParser()`** constructor creates a new `DOMParser` object. This object can be used to parse the text of a document using the `parseFromString()` method.

Syntax
------

```js
new DOMParser()
```

### Parameters

None.

### Return value

A new `DOMParser` object. This object can be used to parse the text of a document using the `parseFromString()` method.

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-domparser-constructor-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


DOMParser: parseFromString() method - Web APIs

DOMParser: parseFromString() method
===================================

The **`parseFromString()`** method of the `DOMParser` interface parses a string containing either HTML or XML, returning an `HTMLDocument` or an `XMLDocument`.

Syntax
------

```js
parseFromString(string, mimeType)
```

### Parameters

`string`

 The string to be parsed. It must contain either an
 HTML, xml, XHTML, or
 svg document.

`mimeType`

A string. This string determines whether the XML parser or the HTML parser is used to parse the string. Valid values are:

* `text/html`
* `text/xml`
* `application/xml`
* `application/xhtml+xml`
* `image/svg+xml`

A value of `text/html` will invoke the HTML parser, and the method will return an `HTMLDocument`. Any `<script>` element gets marked non-executable, and the contents of `<noscript>` are parsed as markup.

The other valid values (`text/xml`, `application/xml`, `application/xhtml+xml`, and `image/svg+xml`) are functionally equivalent. They all invoke the XML parser, and the method will return a `XMLDocument`.

Any other value is invalid and will cause a `TypeError` to be thrown.

### Return value

 An `HTMLDocument` or an `XMLDocument`, depending on the
 `mimeType` argument.

Examples
--------

### Parsing XML, SVG, and HTML

Note that a MIME type of `text/html` will invoke the HTML parser, and any other valid MIME type will invoke the XML parser. The `application/xml` and `image/svg+xml` MIME types in the example below are functionally identical — the latter does not include any SVG-specific parsing rules. Distinguishing between the two serves only to clarify the code's intent.

```js
const parser = new DOMParser();

const xmlString = "<warning>Beware of the tiger</warning>";
const doc1 = parser.parseFromString(xmlString, "application/xml");
// XMLDocument

const svgString = '<circle cx="50" cy="50" r="50"/>';
const doc2 = parser.parseFromString(svgString, "image/svg+xml");
// XMLDocument

const htmlString = "<strong>Beware of the leopard</strong>";
const doc3 = parser.parseFromString(htmlString, "text/html");
// HTMLDocument

console.log(doc1.documentElement.textContent);
// "Beware of the tiger"

console.log(doc2.firstChild.tagName);
// "circle"

console.log(doc3.body.firstChild.textContent);
// "Beware of the leopard"
```

### Error handling

When using the XML parser with a string that doesn't represent well-formed XML, the `XMLDocument` returned by `parseFromString` will contain a `<parsererror>` node describing the nature of the parsing error.

```js
const parser = new DOMParser();

const xmlString = "<warning>Beware of the missing closing tag";
const doc = parser.parseFromString(xmlString, "application/xml");
const errorNode = doc.querySelector("parsererror");
if (errorNode) {
  // parsing failed
} else {
  // parsing succeeded
}
```

Additionally, the parsing error may be reported to the browser's JavaScript console.

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-domparser-parsefromstring-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `XMLSerializer`
* `JSON.parse()` - counterpart for `JSON` documents.


MediaElementAudioSourceNode: MediaElementAudioSourceNode() constructor - Web APIs

MediaElementAudioSourceNode: MediaElementAudioSourceNode() constructor
======================================================================

The **`MediaElementAudioSourceNode()`** constructor creates a new `MediaElementAudioSourceNode` object instance.

Syntax
------

```js
new MediaElementAudioSourceNode(context, options)
```

### Parameters

`context`

An `AudioContext` representing the audio context you want the node to be associated with.

`options`

An object defining the properties you want the `MediaElementAudioSourceNode` to have:

`mediaElement`

An `HTMLMediaElement` that will be used as the source for the audio.

`channelCount`

 An integer used to determine how many channels are used when up-mixing and down-mixing connections to any inputs to the node. (See
 `AudioNode.channelCount` for more information.) Its usage and precise
 definition depend on the value of `channelCountMode`.

`channelCountMode`

 A string describing the way channels must be matched between
 the node's inputs and outputs. (See `AudioNode.channelCountMode` for more
 information including default values.)

`channelInterpretation`

 A string describing the meaning of the channels. This
 interpretation will define how audio up-mixing and down-mixing will happen.
 The possible values are `"speakers"` or `"discrete"`. (See
 `AudioNode.channelInterpretation` for more information including default
 values.)

### Return value

A new `MediaElementAudioSourceNode` object instance.

Examples
--------

```js
const ac = new AudioContext();
const mediaElement = document.createElement("audio");

const myAudioSource = new MediaElementAudioSourceNode(ac, {
  mediaElement,
});
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-mediaelementaudiosourcenode-mediaelementaudiosourcenode |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


MediaElementAudioSourceNode: mediaElement property - Web APIs

MediaElementAudioSourceNode: mediaElement property
==================================================

 The `MediaElementAudioSourceNode` interface's
 read-only **`mediaElement`** property indicates the
 `HTMLMediaElement` that contains the audio track from which the node is
 receiving audio.

 This stream was specified when the node was first created,
 either using the `MediaElementAudioSourceNode()` constructor or the
 `AudioContext.createMediaElementSource()` method.

Value
-----

 An `HTMLMediaElement` representing the element which contains the source
 of audio for the node.

Examples
--------

```js
const audioCtx = new window.AudioContext();
const audioElem = document.querySelector("audio");

let options = {
  mediaElement: audioElem,
};

let source = new MediaElementAudioSourceNode(audioCtx, options);
console.log(source.mediaElement);
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-mediaelementaudiosourcenode-mediaelement |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


RTCPeerConnectionIceErrorEvent: address property - Web APIs

RTCPeerConnectionIceErrorEvent: address property
================================================

 The `RTCPeerConnectionIceErrorEvent` property
 **`address`** is a string which indicates the local IP address
 being used to communicate with the STUN or TURN server
 during negotiations. The error which occurred involved this address.

Value
-----

 A string which specifies the local IP address of the network
 connection to the ICE server with which negotiations were occurring when the error
 occurred. This address identifies the network interface on the local device which is
 being used to attempt to establish the connection to the remote peer.

 This can be useful on multi-homed systems—devices with more than one network
 connection—to determine which network interface is being used. For example, on a mobile
 phone, there are typically at least two network interfaces available: the cellular
 connection and a Wi-Fi connection.

 If the local IP address isn't exposed as part of a local candidate, the value of
 `address` is `null`.

Examples
--------

 This example creates a handler for
 `icecandidateerror` events
 which creates human-readable messages describing the local network interface for the
 connection as well as the ICE server that was being used to try to open the connection,
 then calls a function to display those as well as the event's
 `errorText` property's
 contents.

```js
pc.addEventListener("icecandidateerror", (event) => {
  let networkInfo = `[Local interface: ${event.address}:${event.port}`;
  let iceServerInfo = `[ICE server: ${event.url}`;

  showMessage(errorText, iceServerInfo, networkInfo);
});
```

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers # dom-rtcpeerconnectioniceerrorevent-address |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


NavigationCurrentEntryChangeEvent: navigationType property - Web APIs

NavigationCurrentEntryChangeEvent: navigationType property
==========================================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`navigationType`** read-only property of the `NavigationCurrentEntryChangeEvent` interface returns the type of the navigation that resulted in the change. The property may be `null` if the change occurs due to `Navigation.updateCurrentEntry()`.

Value
-----

An enumerated value representing the type of navigation.

The possible values are:

* `push`: A new location is navigated to, causing a new entry to be pushed onto the history list.
* `reload`: The `Navigation.currentEntry` is reloaded.
* `replace`: The `Navigation.currentEntry` is replaced with a new history entry. This new entry will reuse the same `key`, but be assigned a different `id`.
* `traverse`: The browser navigates from one existing history entry to another existing history entry.
Examples
--------

```js
navigation.addEventListener("currententrychange", (event) => {
  console.log(event.navigationType);
});
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-navigationcurrententrychangeevent-navigationtype-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


NavigationCurrentEntryChangeEvent: from property - Web APIs

NavigationCurrentEntryChangeEvent: from property
================================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`from`** read-only property of the `NavigationCurrentEntryChangeEvent` interface returns the `NavigationHistoryEntry` that was navigated from.

Value
-----

A `NavigationHistoryEntry` object.

Examples
--------

```js
navigation.addEventListener("currententrychange", (event) => {
  console.log(event.from);
});
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-navigationcurrententrychangeevent-from-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


NavigationCurrentEntryChangeEvent: NavigationCurrentEntryChangeEvent() constructor - Web APIs

NavigationCurrentEntryChangeEvent: NavigationCurrentEntryChangeEvent() constructor
==================================================================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`NavigationCurrentEntryChangeEvent()`** constructor creates a new `NavigationCurrentEntryChangeEvent` object.

Syntax
------

```js
new NavigationCurrentEntryChangeEvent(type, init)
```

### Parameters

`type`

A string representing the type of event. In the case of `NavigationCurrentEntryChangeEvent` this is always `event`.

`init`

An object containing the following properties:

`destination`

A `NavigationHistoryEntry` object representing the location being navigated to.

`navigationType` Optional

The type of the navigation that resulted in the change. Possible values are `push`, `reload`, `replace`, and `traverse`. Defaults to `null`.

Examples
--------

A developer would not use this constructor manually. A new `NavigationCurrentEntryChangeEvent` object is constructed when a handler is invoked as a result of the `currententrychange` event firing.

```js
navigation.addEventListener("currententrychange", (event) => {
  console.log(event.navigationType);
});
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # the-navigationcurrententrychangeevent-interface |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


NDEFMessage: NDEFMessage() constructor - Web APIs

NDEFMessage: NDEFMessage() constructor
======================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`NDEFMessage()`** constructor creates a new `NDEFMessage` object, initialized with the given NDEF records.

Syntax
------

```js
new NDEFMessage(records)
```

### Parameters

`records`

An array of objects with the following members:

`data` Optional

Contains the data to be transmitted; one of a string, n `ArrayBuffer`, a `TypedArray`, a `DataView`, or an array of nested records.

`encoding` Optional

A string specifying the record's encoding.

`id` Optional

A developer-defined identifier for the record.

`lang` Optional

A valid language tag according to RFC 5646: Tags for Identifying Languages (also known as BCP 47).

`mediaType` Optional

A valid MIME type.

`recordType`

A string indicating the type of data stored in `data`. It must be one of the following values:

`"absolute-url"`

An absolute URL to the data.

`"empty"`

An empty `NDEFRecord`.

`"mime"`

A valid MIME type.

`"smart-poster"`

A smart poster as defined by the NDEF-SMARTPOSTER specification.

`"text"`

Text as defined by the NDEF-TEXT specification.

`"unknown"`

The record type is not known.

`"URL"`

A URL as defined by the NDEF-URI specification.

Specifications
--------------

| Specification |
| --- |
| Web NFC API # dom-ndefmessage-constructor |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


NDEFMessage: records property - Web APIs

NDEFMessage: records property
=============================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

 The `records` property of
 `NDEFMessage` interface represents a list of `NDEFRecord`s
 present in the NDEF message.

Value
-----

A list of `NDEFRecord` object that represent data recorded in the message.

Examples
--------

The following example shows how to read the contents of an NDEF message. It first sets up an event handler for `onreading`, which is passed an instance of `NDEFReadingEvent`. An `NDEFMessage` object is returned from `NDEFReadingEvent.message`. It loops through `message.records` and processes each record based on its message type. The data member is a `DataView`, which allows handling data encoded in UTF-16.

```js
ndefReaderInst.onreading = (event) => {
  const ndefMessage = event.message;
  for (const record of ndefMessage.records) {
    console.log(`Record type: ${record.recordType}`);
    console.log(`MIME type: ${record.mediaType}`);
    console.log(`Record id: ${record.id}`);
    switch (record.recordType) {
      case "text":
        // TODO: Read text record with record data, lang, and encoding.
        break;
      case "url":
        // TODO: Read URL record with record data.
        break;
      default:
      // TODO: Handle other records with record data.
    }
  }
};
```

Specifications
--------------

| Specification |
| --- |
| Web NFC API # dom-ndefmessage-records |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


CSSMathSum: CSSMathSum() constructor - Web APIs

CSSMathSum: CSSMathSum() constructor
====================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

 The **`CSSMathSum()`** constructor creates a
 new `CSSMathSum` object which creates a new `CSSKeywordValue`
 object which represents the result obtained by calling
 `add()`, `sub()`,
 or `toSum()` on `CSSNumericValue`.

Syntax
------

```js
new CSSMathSum(values)
```

### Parameters

`values`

One or more double integers or `CSSNumericValue` objects.

Specifications
--------------

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-cssmathsum-cssmathsum |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


CSSMathSum: values property - Web APIs

CSSMathSum: values property
===========================

 The **`CSSMathSum.values`** read-only property
 of the `CSSMathSum` interface returns a `CSSNumericArray`
 object which contains one or more `CSSNumericValue` objects.

Value
-----

A `CSSNumericArray`.

Specifications
--------------

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-cssmathsum-values |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


Attr: value property - Web APIs

Attr: value property
====================

The **`value`** property of the `Attr` interface contains the value of the attribute.

Value
-----

A string representing the attribute value.

Example
-------

The following example displays the current value of the attribute `test`. Clicking on the button will change it to a different value, and read it again to update the displayed value.

### HTML

```html
<label test="initial value"></label>

<button>Click me to set test to <code>"a new value"</code>…</button>

<p>
  Current value of the <code>test</code> attribute:
  <output id="result">None.</output>
</p>
```

### JavaScript

```js
const element = document.querySelector("label");
const button = document.querySelector("button");
const result = document.querySelector("#result");

const attribute = element.attributes[0];
result.value = attribute.value;

button.addEventListener("click", () => {
  attribute.value = "a new value";
  result.value = attribute.value;
});
```

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-attr-value |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


Attr: namespaceURI property - Web APIs

Attr: namespaceURI property
===========================

 The read-only **`namespaceURI`** property of the `Attr` interface returns the namespace URI of the attribute,
 or `null` if the element is not in a namespace.

 The namespace URI is set at the `Attr` creation and cannot be changed.
 An attribute with a namespace can be created using `Element.setAttributeNS()`.

**Note:** an attribute does not inherit its namespace from the element it is attached to.
 If an attribute is not explicitly given a namespace, it has no namespace.

 The browser does not handle or enforce namespace validation per se. It is up to the JavaScript
 application to do any necessary validation. Note, too, that the namespace prefix, once it
 is associated with a particular attribute node, cannot be changed.

Value
-----

A string containing the URI of the namespace, or `null` if the attribute is not in a namespace.

Example
-------

 The following example shows the results for a prefixed attribute in a case of an HTML element, and of a SVG element.
 As HTML doesn't handle namespaces, it will always return `null` in that case.
 In the case of the SVG element, it will return the URI of the XML namespace, `http://www.w3.org/XML/1998/namespace`.

### HTML

```html
<svg xml:lang="en-US" class="struct" height="1" width="1">Click me</svg>
<label xml:lang="en-US" class="struct"></label>

<p>
  <button>Show value for <svg></button>
  <button>Show value for <label></button>
</p>

<p>
  Namespace URI of the attribute <code>xml:lang</code>:
  <output id="result">None.</output>
</p>
```

### JavaScript

```js
const elements = document.querySelectorAll(".struct");
const buttons = document.querySelectorAll("button");
const outputEl = document.querySelector("#result");

let i = 0;
for (const button of buttons) {
  const element = elements[i];
  button.addEventListener("click", () => {
    const attribute = element.attributes[0];
    outputEl.value = attribute.namespaceURI;
  });
  i++;
}
```

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-attr-namespaceuri |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The properties `Attr.name`, returning the qualified name of the attribute, `Attr.localName`, the local part of the name, and `Attr.prefix`, the namespace prefix.
* The `Element.namespaceURI` property, equivalent to this one but for an `Element`.
* The `Element.setAttributeNS()` method, creating an attribute with a given namespace.


Attr: name property - Web APIs

Attr: name property
===================

The read-only **`name`** property of the `Attr` interface returns the *qualified name* of an attribute, that is the name of the attribute, with the namespace prefix, if any, in front of it. For example, if the local name is `lang` and the namespace prefix is `xml`, the returned qualified name is `xml:lang`.

The qualified name is always in lower case, whatever case at the attribute creation.

Value
-----

A string representing the attribute's qualified name.

Example
-------

The following example displays the qualified name of the first attribute of the two first elements, when we click on the appropriate button.

### HTML

```html
<svg xml:lang="en-US" class="struct" height="1" width="1">Click me</svg>
<label xml:lang="en-US" class="struct"></label>

<p>
  <button>Show value for <svg></button>
  <button>Show value for <label></button>
</p>

<p>
  Qualified name of the attribute <code>xml:lang</code>:
  <output id="result">None.</output>
</p>
```

### JavaScript

```js
const elements = document.querySelectorAll(".struct");
const buttons = document.querySelectorAll("button");
const outputEl = document.querySelector("#result");

let i = 0;
for (const button of buttons) {
  const element = elements[i];
  button.addEventListener("click", () => {
    const attribute = element.attributes[0];
    outputEl.value = attribute.name;
  });
  i++;
}
```

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-attr-name |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The properties `Attr.localName`, returning the local part of the qualified name of the attribute, and `Attr.prefix`, the namespace prefix.
* The `Element.tagName()` property, returning the qualified name of an `Element`.


Attr: localName property - Web APIs

Attr: localName property
========================

The read-only **`localName`** property of the `Attr` interface returns the *local part* of the *qualified name* of an attribute, that is the name of the attribute, stripped from any namespace in front of it. For example, if the qualified name is `xml:lang`, the returned local name is `lang`, if the element supports that namespace.

The local name is always in lower case, whatever case at the attribute creation.

**Note:** HTML only supports a fixed set of namespaces on SVG and MathML elements. These are `xml` (for the `xml:lang` attribute), `xlink` (for the `xlink:href`, `xlink:show`, `xlink:target` and `xlink:title` attributes) and `xpath`.

That means that the local name of an attribute of an HTML element is always be equal to its qualified name: Colons are treated as regular characters. In XML, like in SVG or MathML, the colon denotes the end of the prefix and what is before is the namespace; the local name may be different from the qualified name.

Value
-----

A string representing the local part of the attribute's qualified name.

Example
-------

The following example displays the local name of the first attribute of the two first elements, when we click on the appropriate button. The `<svg>` element is XML and supports namespaces leading to the local name (`lang`) to be different from the qualified name `xml:lang`. The `<label>` element is HTML, that doesn't support namespaces, leading to a local name and the qualified name to be both `xml:lang`.

### HTML

```html
<svg xml:lang="en-US" class="struct" height="1" width="1">Click me</svg>
<label xml:lang="en-US" class="struct"></label>

<p>
  <button>Show value for <svg></button>
  <button>Show value for <label></button>
</p>

<p>
  Local part of the attribute <code>xml:lang</code>:
  <output id="result">None.</output>
</p>
```

### JavaScript

```js
const elements = document.querySelectorAll(".struct");
const buttons = document.querySelectorAll("button");
const outputEl = document.querySelector("#result");

let i = 0;
for (const button of buttons) {
  const element = elements[i];
  button.addEventListener("click", () => {
    const attribute = element.attributes[0];
    outputEl.value = attribute.localName;
  });
  i++;
}
```

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-attr-localname |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The properties `Attr.name`, returning the qualified name of the attribute, and `Attr.prefix`, the namespace prefix.
* The `Element.localName()` property, returning the local name of an `Element`.


Attr: prefix property - Web APIs

Attr: prefix property
=====================

The read-only **`prefix`** property of the `Attr` returns the namespace prefix of the attribute, or `null` if no prefix is specified.

The prefix is always in lower case, whatever case is used at the attribute creation.

**Note:** Only XML supports namespaces. HTML does not. That means that the prefix of an attribute of an HTML element will always be `null`.

Also, only the `xml` (for the `xml:lang` attribute), `xlink` (for the `xlink:href`, `xlink:show`, `xlink:target` and `xlink:title` attributes) and `xpath` namespaces are supported, and only on SVG and MathML elements.

Value
-----

A string containing the prefix of the namespace the attribute belongs too. If none, it returns `null`.

Example
-------

### HTML

```html
<svg xml:lang="en-US" class="struct" height="1" width="1">Click me</svg>
<label xml:lang="en-US" class="struct"></label>

<p>
  <button>Show value for <svg></button>
  <button>Show value for <label></button>
</p>

<p>
  Prefix of the attribute <code>xml:lang</code>:
  <output id="result">None.</output>
</p>
```

### JavaScript

```js
const elements = document.querySelectorAll(".struct");
const buttons = document.querySelectorAll("button");
const outputEl = document.querySelector("#result");

let i = 0;
for (const button of buttons) {
  const element = elements[i];
  button.addEventListener("click", () => {
    const attribute = element.attributes[0];
    outputEl.value = attribute.prefix;
  });
  i++;
}
```

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-attr-prefix |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The properties `Attr.name`, returning the qualified name of the attribute, and `Attr.localName`, its local name.
* The `Element.prefix()` property, returning the namespace prefix of an `Element`.


Attr: ownerElement property - Web APIs

Attr: ownerElement property
===========================

The read-only **`ownerElement`** property of the `Attr` interface returns the `Element` the attribute belongs to.

Value
-----

The `Element` the attribute belongs to, or `null` if the attribute is not linked to an element.

Example
-------

The following example displays the qualified name of the element of the two first elements, when we click on the appropriate button.

### HTML

```html
<svg xml:lang="en-US" class="struct" height="1" width="1">Click me</svg>
<label xml:lang="en-US" class="struct"></label>

<p>
  <button>Show value for <svg></button>
  <button>Show value for <label></button>
</p>

<p>
  Qualified name of the owner element of the attribute <code>xml:lang</code>:
  <output id="result">None.</output>
</p>
```

### JavaScript

```js
const elements = document.querySelectorAll(".struct");
const buttons = document.querySelectorAll("button");
const outputEl = document.querySelector("#result");

let i = 0;
for (const button of buttons) {
  const element = elements[i];
  button.addEventListener("click", () => {
    const attribute = element.attributes[0];
    outputEl.value = attribute.ownerElement.tagName.toLowerCase();
  });
  i++;
}
```

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-attr-ownerelement |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


Attr: specified property - Web APIs

Attr: specified property
========================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The read-only **`specified`** property of the `Attr` interface always returns `true`.

Value
-----

Always returns `true`.

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-attr-specified |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


MediaStreamTrack: stop() method - Web APIs

MediaStreamTrack: stop() method
===============================

The **`stop()`** method of the `MediaStreamTrack` interface stops the track.

Syntax
------

```js
stop()
```

### Parameters

None.

### Return value

None (`undefined`).

Description
-----------

 Calling `stop()` tells the user agent that the track's
 source—whatever that source may be, including files, network streams, or a local camera
 or microphone—is no longer needed by the `MediaStreamTrack`. Since multiple
 tracks may use the same source (for example, if two tabs are using the device's
 microphone), the source itself isn't necessarily immediately stopped. It is instead
 disassociated from the track and the track object is stopped. Once no media tracks are
 using the source, the source may actually be completely stopped.

 Immediately after calling `stop()`, the
 `readyState` property is set to
 `ended`. Note that the `ended` event will not be fired in this situation.

Examples
--------

### Stopping a video stream

 In this example, we see a function which stops a streamed video by calling
 `stop()` on every track on a given `<video>`.

```js
function stopStreamedVideo(videoElem) {
  const stream = videoElem.srcObject;
  const tracks = stream.getTracks();

  tracks.forEach((track) => {
    track.stop();
  });

  videoElem.srcObject = null;
}
```

 This works by obtaining the video element's stream from its
 `srcObject` property. Then the stream's track
 list is obtained by calling its `getTracks()`
 method. From there, all that remains to do is to iterate over the track list using
 `forEach()` and calling each track's `stop()`
 method.

 Finally, `srcObject` is set to `null` to sever the link to the
 `MediaStream` object so it can be released.

Specifications
--------------

| Specification |
| --- |
| Media Capture and Streams # dom-mediastreamtrack-stop |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `MediaStreamTrack`, the interface it belongs to.
* `MediaStreamTrack.readyState`
* `ended`


MediaStreamTrack: getConstraints() method - Web APIs

MediaStreamTrack: getConstraints() method
=========================================

 The **`getConstraints()`** method of
 the `MediaStreamTrack` interface returns a
 `MediaTrackConstraints` object containing the set of constraints most
 recently established for the track using a prior call to
 `applyConstraints()`. These
 constraints indicate values and ranges of values that the website or application has
 specified are required or acceptable for the included constrainable properties.

 Constraints can be used to ensure that the media meets certain guidelines you prefer.
 For example, you may prefer high definition video but require that the frame rate be a
 little low to help keep the data rate low enough not overtax the network. Constraints
 can also specify ideal and/or acceptable sizes or ranges of sizes. See Capabilities, constraints, and settings for details on how to work with constrainable properties.

Syntax
------

```js
getConstraints()
```

### Parameters

None.

### Return value

 A `MediaTrackConstraints` object which indicates the constrainable
 properties the website or app most recently set using
 `applyConstraints()`. The properties
 in the returned object are listed in the same order as when they were set, and only
 properties specifically set by the site or app are included.

**Note:** The returned set of constraints doesn't necessarily describe
 the actual state of the media. Even if any of the constraints couldn't be met, they
 are still included in the returned object as originally set by the site's code. To get
 the currently active settings for all constrainable properties, you should instead
 call `getSettings()`.

Examples
--------

 This example obtains the current constraints for a track, sets the
 `facingMode`, and applies the updated
 constraints.

```js
function switchCameras(track, camera) {
  const constraints = track.getConstraints();
  constraints.facingMode = camera;
  track.applyConstraints(constraints);
}
```

Specifications
--------------

| Specification |
| --- |
| Media Capture and Streams # dom-mediastreamtrack-getconstraints |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


MediaStreamTrack: enabled property - Web APIs

MediaStreamTrack: enabled property
==================================

 The **`enabled`** property of the
 `MediaStreamTrack` interface is a Boolean value which is
 `true` if the track is allowed to render the source stream or
 `false` if it is not. This can be used to intentionally mute a
 track.

 When enabled, a track's data is output from the source to the
 destination; otherwise, empty frames are output.

 In the case of audio, a disabled track generates frames of silence (that is, frames in
 which every sample's value is 0). For video tracks, every frame is filled entirely with
 black pixels.

 The value of `enabled`, in essence, represents what a typical user would
 consider the muting state for a track, whereas the `muted` property indicates a state in which the track is temporarily unable to output
 data, such as a scenario in which frames have been lost in transit.

**Note:** If the track has been disconnected, the value of this property
 can be changed, but has no effect.

Value
-----

 When `true`, `enabled` indicates that the track is permitted to
 render its actual media to the output. When `enabled` is set to
 `false`, the track only generates empty frames.

 Empty audio frames have every sample's value set to 0. Empty video frames have every
 pixel set to black.

**Note:** When implementing a mute/unmute feature, you should use the
 `enabled` property.

Usage notes
-----------

 If the `MediaStreamTrack` represents the video input from a camera,
 disabling the track by setting `enabled` to `false` also updates
 device activity indicators to show that the camera is not currently recording or
 streaming. For example, the green "in use" light next to the camera in iMac and MacBook
 computers turns off while the track is muted in this way.

Example
-------

This example demonstrates a `click` event handler for a pause button.

```js
pauseButton.onclick = (evt) => {
  const newState = !myAudioTrack.enabled;

  pauseButton.innerHTML = newState ? "▶" : "⏸";
  myAudioTrack.enabled = newState;
};
```

 This creates a variable, `newState`, which is the opposite of the current
 value of `enabled`, then uses that to select either the Emoji character for
 the "play" icon or the character for the "pause" icon as the new
 `innerHTML` of the pause button's element.

Finally, the new value of `enabled` is saved, making the change take effect.

Specifications
--------------

| Specification |
| --- |
| Media Capture and Streams # dom-mediastreamtrack-enabled |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Media Capture and Streams API
* `MediaStream`
* `MediaStreamTrack`
* WebRTC


MediaStreamTrack: contentHint property - Web APIs

MediaStreamTrack: contentHint property
======================================

The **`contentHint`** property of the `MediaStreamTrack` interface is a string that hints at the type of content the track contains. Allowable values depend on the value of the `MediaStreamTrack.kind` property.

Value
-----

A string with one of the following values:

`""`

No `contentHint` has been set.

`"speech"`

The track should be treated as if it contains speech data. When setting this value, the value of `MediaStreamTrack.kind` must be `"audio"`.

`"speech-recognition"`

The track should be treated as if it contains data for the purpose of speech recognition by a machine. When setting this value, the value of `MediaStreamTrack.kind` must be `"audio"`.

`"music"`

The track should be treated as if it contains music. When setting this value, the value of `MediaStreamTrack.kind` must be `"audio"`.

`"motion"`

The track should be treated as if it contains video where motion is important. For example, webcam video, movies or video games. When setting this value, the value of `MediaStreamTrack.kind` must be `"video"`.

`"detail"`

The track should be treated as if video details are extra important. For example, presentations or web pages with text content, painting or line art. When setting this value, the value of `MediaStreamTrack.kind` must be `"video"`.

`"text"`

The track should be treated as if video details are extra important, and that significant sharp edges and areas of consistent color can occur frequently. For example, presentations or web pages with text content. When setting this value, the value of `MediaStreamTrack.kind` must be `"video"`.

Examples
--------

### A function that sets the contentHint

This function takes a stream and a `contentHint` value, and applies the hint to each track. See the full example here, showing how different `contentHint` values change how the tracks display.

```js
function setVideoTrackContentHints(stream, hint) {
  const tracks = stream.getVideoTracks();
  tracks.forEach((track) => {
    if ("contentHint" in track) {
      track.contentHint = hint;
      if (track.contentHint !== hint) {
        console.error(`Invalid video track contentHint: "${hint}"`);
      }
    } else {
      console.error("MediaStreamTrack contentHint attribute not supported");
    }
  });
}
```

Specifications
--------------

| Specification |
| --- |
| MediaStreamTrack Content Hints # dom-mediastreamtrack-contenthint |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


MediaStreamTrack: label property - Web APIs

MediaStreamTrack: label property
================================

The **`label`** read-only property of the `MediaStreamTrack` interface returns a string containing a user agent-assigned label that identifies the track source, as in `"internal microphone"`.

 The string may be left empty and is empty as long as no source has been connected.
 When the track is disassociated from its source, the label is not changed.

Syntax
------

```js
const label = track.label
```

Specifications
--------------

| Specification |
| --- |
| Media Capture and Streams # dom-mediastreamtrack-label |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC


MediaStreamTrack: id property - Web APIs

MediaStreamTrack: id property
=============================

 The **`id`** read-only property of the `MediaStreamTrack` interface returns a
 string containing a unique identifier (GUID) for the track, which is
 generated by the user agent.

Syntax
------

```js
const id = track.id
```

Specifications
--------------

| Specification |
| --- |
| Media Capture and Streams # dom-mediastreamtrack-id |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC


MediaStreamTrack: unmute event - Web APIs

MediaStreamTrack: unmute event
==============================

The **`unmute`** event is sent to a `MediaStreamTrack` when the track's source is once again able to provide media data after a period of not being able to do so.

This ends the `muted` state that began with the `mute` event.

**Note:** The condition that most people think of as "muted" (that is, a user-controllable way to silence a track) is actually managed using the `MediaStreamTrack.enabled` property, for which there are no events.

This event is not cancelable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("unmute", (event) => {});

onunmute = (event) => {};
```

Event type
----------

A generic `Event`.

Examples
--------

In this example, event handlers are established for the `mute` and `unmute` events in order to detect when the media is not flowing from the source for the `MediaStreamTrack` stored in the variable `musicTrack`.

```js
musicTrack.addEventListener(
  "mute",
  (event) => {
    document.getElementById("timeline-widget").style.backgroundColor = "#aaa";
  },
  false,
);

musicTrack.addEventListener(
  "unmute",
  (event) => {
    document.getElementById("timeline-widget").style.backgroundColor = "#fff";
  },
  false,
);
```

With these event handlers in place, when the track `musicTrack` enters its `muted` state, the element with the ID `timeline-widget` gets its background color changed to `#aaa`. When the track exits the muted state—detected by the arrival of an `unmuted` event—the background color is restored to white.

You can also use the `onunmute` event handler property to set up a handler for this event; similarly, the `onmute` event handler is available for setting up a handler for the `mute` event. The following example shows this:

```js
musicTrack.onmute = (event) => {
  document.getElementById("timeline-widget").style.backgroundColor = "#aaa";
};

musicTrack.mute = (event) => {
  document.getElementById("timeline-widget").style.backgroundColor = "#fff";
};
```

### Unmute tracks through receivers

The following example shows how to unmute tracks using receivers.

```js
// Peer 1 (Receiver)
audioTrack.addEventListener("unmute", (event) => {
  // Do something in UI
});

videoTrack.addEventListener("unmute", (event) => {
  // Do something in UI
});

// Peer 2 (Sender)
const transceivers = peer.getTransceivers();

const audioTrack = transceivers[0];
audioTrack.direction = "sendrecv";

const videoTrack = transceivers[1];
videoTrack.direction = "sendrecv";
```

`transceivers` is an array of `RTCRtpTransceiver` where you can find the audio or video track sent and received. For more information, see the `direction` article.

Specifications
--------------

| Specification |
| --- |
| Media Capture and Streams # event-mediastreamtrack-unmute |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The `mute` event


MediaStreamTrack: ended event - Web APIs

MediaStreamTrack: ended event
=============================

The **`ended`** event of the `MediaStreamTrack` interface is fired when playback or streaming has stopped because the end of the media was reached or because no further data is available.

This event is not cancelable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("ended", (event) => {});

onended = (event) => {};
```

Event type
----------

A generic `Event`.

Usage notes
-----------

`ended` events fire when the media stream track's source permanently stops sending data on the stream. There are various ways this can happen, including:

* There is no more data left to send.
* The user revoked the permissions needed for the data to be sent.
* The hardware generating the source data has been removed or ejected.
* A remote peer has permanently stopped sending data; pausing media *does not* generate an `ended` event.
Examples
--------

This example sets up an event handler for the `ended` event, which changes an on-screen icon to indicate that the track is no longer active.

```js
track.addEventListener("ended", () => {
  let statusElem = document.getElementById("status-icon");
  statusElem.src = "/images/stopped-icon.png";
});
```

You can also set up the event handler using the `onended` property:

```js
track.onended = () => {
  let statusElem = document.getElementById("status-icon");

  statusElem.src = "/images/stopped-icon.png";
};
```

Specifications
--------------

| Specification |
| --- |
| Media Capture and Streams # dom-mediastreamtrack-onended |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The HTMLMediaElement `playing` event
* The HTMLMediaElement `waiting` event
* The HTMLMediaElement `seeking` event
* `<audio>`
* `<video>`
* The HTMLMediaElement `ended` event
* The AudioScheduledSourceNode `ended` event


MediaStreamTrack: muted property - Web APIs

MediaStreamTrack: muted property
================================

 The **`muted`** read-only property of the
 `MediaStreamTrack` interface returns a boolean value
 indicating whether or not the track is currently unable to provide media output.

**Note:** To implement a way for users to mute and unmute a track, use the
 `enabled` property. When a track is disabled
 by setting `enabled` to `false`, it generates only empty frames
 (audio frames in which every sample is 0, or video frames in which every pixel is
 black).

Value
-----

 A boolean which is `true` if the track is currently muted, or
 `false` if the track is currently unmuted.

**Note:** When possible, avoid polling `muted` to monitor the track's muting status.
 Instead, add event listeners for the `mute` and `unmute` events.

Examples
--------

 This example counts the number of tracks in an array of `MediaStreamTrack`
 objects which are currently muted.

```js
let mutedCount = 0;

trackList.forEach((track) => {
  if (track.muted) {
    mutedCount += 1;
  }
});
```

Specifications
--------------

| Specification |
| --- |
| Media Capture and Streams # dom-mediastreamtrack-muted |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


MediaStreamTrack: getSettings() method - Web APIs

MediaStreamTrack: getSettings() method
======================================

 The **`getSettings()`** method of the
 `MediaStreamTrack` interface returns a `MediaTrackSettings`
 object containing the current values of each of the constrainable properties for the
 current `MediaStreamTrack`.

See Capabilities, constraints, and settings for details on how to work with constrainable properties.

Syntax
------

```js
getSettings()
```

### Parameters

None.

### Return value

 A `MediaTrackSettings` object describing the current configuration of the
 track's constrainable properties.

**Note:** The returned object identifies the current values of every
 constrainable property, including those which are platform defaults rather than having
 been expressly set by the site's code. To instead fetch the most-recently established
 constraints for the track's properties, as specified by the site's code, use
 `getConstraints()`.

Specifications
--------------

| Specification |
| --- |
| Media Capture and Streams # dom-mediastreamtrack-getsettings |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


MediaStreamTrack: applyConstraints() method - Web APIs

MediaStreamTrack: applyConstraints() method
===========================================

The **`applyConstraints()`** method of the `MediaStreamTrack` interface applies a set of constraints to the track; these constraints let the website or app establish ideal values and acceptable ranges of values for the constrainable properties of the track, such as frame rate, dimensions, echo cancellation, and so forth.

 Constraints can be used to ensure that the media meets certain guidelines you prefer.
 For example, you may prefer high-density video but require that the frame rate be a little low to help keep the data rate low enough not overtax the network.
 Constraints can also specify ideal and/or acceptable sizes or ranges of sizes.
 See Applying constraints in Capabilities, constraints, and settings for more information on how to apply your preferred constraints.

Syntax
------

```js
applyConstraints()
applyConstraints(constraints)
```

### Parameters

`constraints` Optional

 A `MediaTrackConstraints` object listing the constraints to apply to the track's constrainable properties; any existing constraints are replaced with the new values specified, and any constrainable properties not included are restored to their default constraints.
 If this parameter is omitted, all currently set custom constraints are cleared.
 This object represents the basic set of constraints that must apply for the `Promise` to resolve.
 The object may contain an advanced property containing an array of additional `MediaTrackConstraints` objects, which are treated as exact requires.

### Return value

 A `Promise` which resolves when the constraints have been successfully applied.
 If the constraints cannot be applied, the promise is rejected with a `OverconstrainedError` that is a `DOMException` whose name is `OverconstrainedError` with additional parameters, and, to indicate that the constraints could not be met.
 This can happen if the specified constraints are too strict to find a match when attempting to configure the track.

Examples
--------

 The following shows how to specify a basic and advanced set of constraints.
 It specifies that the page or web app needs a width between 640 and 1280 and a height between 480 and 720, with the later number in each pair being preferred.
 The advanced property further specifies that an image size of 1920 by 1280 is the preferred or an aspect ratio of 1.333 if that is not available.
 Note that these constraints also illustrate what the spec refers to as a *backoff strategy*.

```js
const constraints = {
  width: { min: 640, ideal: 1280 },
  height: { min: 480, ideal: 720 },
  advanced: [{ width: 1920, height: 1280 }, { aspectRatio: 1.333 }],
};

navigator.mediaDevices.getUserMedia({ video: true }).then((mediaStream) => {
  const track = mediaStream.getVideoTracks()[0];
  track
    .applyConstraints(constraints)
    .then(() => {
      // Do something with the track such as using the Image Capture API.
    })
    .catch((e) => {
      // The constraints could not be satisfied by the available devices.
    });
});
```

Specifications
--------------

| Specification |
| --- |
| Media Capture and Streams # dom-mediastreamtrack-applyconstraints |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* MediaStream Image Capture API


MediaStreamTrack: getCapabilities() method - Web APIs

MediaStreamTrack: getCapabilities() method
==========================================

 The **`getCapabilities()`** method of
 the `MediaStreamTrack` interface returns a
 `MediaTrackCapabilities` object which specifies the values or range of
 values which each constrainable property, based upon the platform and user agent.

 Once you know what the browser's capabilities are, your script can use
 `applyConstraints()` to ask for the
 track to be configured to match ideal or acceptable settings. See Capabilities, constraints, and settings for details on how to work with constrainable properties.

Syntax
------

```js
getCapabilities()
```

### Parameters

None.

### Return value

A `MediaTrackCapabilities` object which specifies the value or range of values which are supported for each of the user agent's supported constrainable properties, containing the following members:

`deviceId`

A `ConstrainDOMString` object containing the device ID.

`groupId`

A `ConstrainDOMString` object containing a group ID.

`autoGainControl`

 A `ConstrainBoolean` object reporting if the source can do auto gain control.
 If the feature can be controlled by a script the source will report both true and false as possible values.

`channelCount`

A `ConstrainULong` containing the channel count or range of channel counts.

`echoCancellation`

 A `ConstrainBoolean` object reporting if the source can do echo cancellation.
 If the feature can be controlled by a script the source will report both true and false as possible values.

`latency`

A `ConstrainDouble` containing the latency or range of latencies.

`noiseSuppression`

 A `ConstrainBoolean` object reporting if the source can do noise suppression.
 If the feature can be controlled by a script the source will report both true and false as possible values.

`sampleRate`

A `ConstrainULong` containing the sample rate or range of sample rates.

`sampleSize`

A `ConstrainULong` containing the sample size or range of sample sizes.

`aspectRatio`

A `ConstrainDouble` containing the video aspect ratio (width in pixels divided by height in pixels) or range of aspect ratios.

`facingMode`

A `ConstrainDOMString` object containing the camera facing mode. A camera may report multiple facings, for example "left" and "user".

`frameRate`

A `ConstrainDouble` containing the frame rate or range of frame rates which are acceptable.

`height`

A `ConstrainULong` containing the video height or range of heights in pixels.

`width`

A `ConstrainULong` containing the video width or range of widths in pixels.

`resizeMode`

A `ConstrainDOMString` object containing the mode or an array of modes the UA can use to derive the resolution of the video track.

Specifications
--------------

| Specification |
| --- |
| Media Capture and Streams # dom-mediastreamtrack-getcapabilities |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `InputDeviceInfo.getCapabilities()`, which also return a `MediaTrackCapabilities` object.


MediaStreamTrack: kind property - Web APIs

MediaStreamTrack: kind property
===============================

 The **`kind`** read-only property of the `MediaStreamTrack` interface returns a string set to `"audio"` if the track is an audio track and to `"video"` if it is a video track.
 It doesn't change if the track is disassociated from its source.

Value
-----

The possible values are a string with one of the following values:

* `"audio"`: the track is an audio track.
* `"video"`: the track is a video track.
Specifications
--------------

| Specification |
| --- |
| Media Capture and Streams # dom-mediastreamtrack-kind |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* WebRTC


MediaStreamTrack: mute event - Web APIs

MediaStreamTrack: mute event
============================

The **`mute`** event is sent to a `MediaStreamTrack` when the track's source is temporarily unable to provide media data.

When the track is once again able to produce media output, an `unmute` event is sent.

During the time between the `mute` event and the `unmute` event, the value of the track's `muted` property is `true`.

**Note:** The condition that most people think of as "muted" (that is, a user-toggled state of silencing a track) is actually managed using the `MediaStreamTrack.enabled` property, for which there are no events.

This event is not cancelable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("mute", (event) => {});

onmute = (event) => {};
```

Event type
----------

A generic `Event`.

Examples
--------

In this example, event handlers are established for the `mute` and `unmute` events in order to detect when the media is not flowing from the source for the `MediaStreamTrack` referenced by `musicTrack`.

```js
musicTrack.addEventListener(
  "mute",
  (event) => {
    document.getElementById("timeline-widget").style.backgroundColor = "#aaa";
  },
  false,
);

musicTrack.addEventListener(
  "unmute",
  (event) => {
    document.getElementById("timeline-widget").style.backgroundColor = "#fff";
  },
  false,
);
```

With these event handlers in place, when the track `musicTrack` enters its `muted` state, the element with the ID `timeline-widget` gets its background color changed to `#aaa`. When the track exits the muted state—detected by the arrival of an `unmute` event—the background color is restored to white.

You can also use the `onmute` event handler property to set up a handler for this event; similarly, the `onunmute` event handler is available for setting up a handler for the `unmute` event. The following example shows this:

```js
musicTrack.onmute = (event) => {
  document.getElementById("timeline-widget").style.backgroundColor = "#aaa";
};

musicTrack.onunmute = (event) => {
  document.getElementById("timeline-widget").style.backgroundColor = "#fff";
};
```

### Mute tracks through receivers

The following example shows how to mute tracks using receivers.

```js
// Peer 1 (Receiver)
audioTrack.addEventListener("mute", (event) => {
  // Do something in UI
});

videoTrack.addEventListener("mute", (event) => {
  // Do something in UI
});

// Peer 2 (Sender)
const transceivers = peer.getTransceivers();

const audioTrack = transceivers[0];
audioTrack.direction = "recvonly";

const videoTrack = transceivers[1];
videoTrack.direction = "recvonly";
```

`transceivers` is an array of `RTCRtpTransceiver` where you can find the audio or video track sent and received. For more information, see the `direction` article.

Specifications
--------------

| Specification |
| --- |
| Media Capture and Streams # dom-mediastreamtrack-onmute |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `unmute` event
* `direction`


MediaStreamTrack: readyState property - Web APIs

MediaStreamTrack: readyState property
=====================================

The **`readyState`** read-only property of the `MediaStreamTrack` interface returns an enumerated value giving the status of the track.

Value
-----

It takes one of the following values:

* `"live"` which indicates that an input is connected and does its
 best-effort in providing real-time data. In that case, the output of data can be
 switched on or off using the `MediaStreamTrack.enabled` property.
* `"ended"` which indicates that the input is not giving any more data and
 will never provide new data.
Specifications
--------------

| Specification |
| --- |
| Media Capture and Streams # dom-mediastreamtrack-readystate |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Media Capture and Streams API
* WebRTC
* The `ended` event


MediaStreamTrack: clone() method - Web APIs

MediaStreamTrack: clone() method
================================

 The **`clone()`** method of the `MediaStreamTrack`
 interface creates a duplicate of the `MediaStreamTrack`. This new
 `MediaStreamTrack` object is identical except for its unique
 `id`.

Syntax
------

```js
clone()
```

### Parameters

None.

### Return value

 A new `MediaStreamTrack` instance which is identical to the one
 `clone()` was called, except for its new unique
 `id`.

Specifications
--------------

| Specification |
| --- |
| Media Capture and Streams # dom-mediastreamtrack-clone |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


PerformanceObserverEntryList: getEntriesByName() method - Web APIs

PerformanceObserverEntryList: getEntriesByName() method
=======================================================

The **`getEntriesByName()`** method of the `PerformanceObserverEntryList` interface returns a list of explicitly observed performance entry objects for a given `name` and `entry type`. The list's members are determined by the set of entry types specified in the call to the `observe()` method. The list is available in the observer's callback function (as the first parameter in the callback).

Syntax
------

```js
getEntriesByName(name)
getEntriesByName(name, type)
```

### Parameters

`name`

A string representing the name of the entry to retrieve.

`type` Optional

A string representing the type of entry to retrieve such as `"mark"`. The valid entry types are listed in `PerformanceEntry.entryType`.

### Return value

A list of explicitly *observed* performance entry objects that have the specified `name` and `type`. If the `type` argument is not specified, only the `name` will be used to determine the entries to return. The items will be in chronological order based on the entries' `startTime`. If no objects meet the specified criteria, an empty list is returned.

Examples
--------

### Working with getEntries, getEntriesByName and getEntriesByType

The following example shows the difference between the `getEntries()`, `getEntriesByName()`, and `getEntriesByType()` methods.

```js
const observer = new PerformanceObserver((list, obs) => {
  // Log all entries
  let perfEntries = list.getEntries();
  perfEntries.forEach((entry) => {
    console.log(`${entry.name}'s duration: ${entry.duration}`);
  });

  // Log entries named "debugging" with type "measure"
  perfEntries = list.getEntriesByName("debugging", "measure");
  perfEntries.forEach((entry) => {
    console.log(`${entry.name}'s duration: ${entry.duration}`);
  });

  // Log entries with type "mark"
  perfEntries = list.getEntriesByType("mark");
  perfEntries.forEach((entry) => {
    console.log(`${entry.name}'s startTime: ${entry.startTime}`);
  });
});

// Subscribe to various performance event types
observer.observe({
  entryTypes: ["mark", "measure", "navigation", "resource"],
});
```

Specifications
--------------

| Specification |
| --- |
| Performance Timeline # dom-performanceobserverentrylist-getentriesbyname |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


PerformanceObserverEntryList: getEntries() method - Web APIs

PerformanceObserverEntryList: getEntries() method
=================================================

The **`getEntries()`** method of the `PerformanceObserverEntryList` interface returns a list of explicitly observed performance entry objects. The list's members are determined by the set of entry types specified in the call to the `observe()` method. The list is available in the observer's callback function (as the first parameter in the callback).

Syntax
------

```js
getEntries()
```

### Return value

A list of explicitly observed `PerformanceEntry` objects. The items will be in chronological order based on the entries' `startTime`. If no objects are found, an empty list is returned.

Examples
--------

### Working with getEntries, getEntriesByName and getEntriesByType

The following example shows the difference between the `getEntries()`, `getEntriesByName()`, and `getEntriesByType()` methods.

```js
const observer = new PerformanceObserver((list, obs) => {
  // Log all entries
  let perfEntries = list.getEntries();
  perfEntries.forEach((entry) => {
    console.log(`${entry.name}'s duration: ${entry.duration}`);
  });

  // Log entries named "debugging" with type "measure"
  perfEntries = list.getEntriesByName("debugging", "measure");
  perfEntries.forEach((entry) => {
    console.log(`${entry.name}'s duration: ${entry.duration}`);
  });

  // Log entries with type "mark"
  perfEntries = list.getEntriesByType("mark");
  perfEntries.forEach((entry) => {
    console.log(`${entry.name}'s startTime: ${entry.startTime}`);
  });
});

// Subscribe to various performance event types
observer.observe({
  entryTypes: ["mark", "measure", "navigation", "resource"],
});
```

Specifications
--------------

| Specification |
| --- |
| Performance Timeline # dom-performanceobserverentrylist-getentries |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


PerformanceObserverEntryList: getEntriesByType() method - Web APIs

PerformanceObserverEntryList: getEntriesByType() method
=======================================================

The **`getEntriesByType()`** method of the `PerformanceObserverEntryList` returns a list of explicitly *observed* performance entry objects for a given performance entry type. The list's members are determined by the set of entry types specified in the call to the `observe()` method. The list is available in the observer's callback function (as the first parameter in the callback).

Syntax
------

```js
getEntriesByType(type)
```

### Parameters

`type`

The type of entry to retrieve such as `"mark"`. The valid entry types are listed in `PerformanceEntry.entryType`.

### Return value

A list of explicitly *observed* `PerformanceEntry` objects that have the specified `type`. The items will be in chronological order based on the entries' `startTime`. If no objects have the specified `type`, or no argument is provided, an empty list is returned.

Examples
--------

### Working with getEntries, getEntriesByName and getEntriesByType

The following example shows the difference between the `getEntries()`, `getEntriesByName()`, and `getEntriesByType()` methods.

```js
const observer = new PerformanceObserver((list, obs) => {
  // Log all entries
  let perfEntries = list.getEntries();
  perfEntries.forEach((entry) => {
    console.log(`${entry.name}'s duration: ${entry.duration}`);
  });

  // Log entries named "debugging" with type "measure"
  perfEntries = list.getEntriesByName("debugging", "measure");
  perfEntries.forEach((entry) => {
    console.log(`${entry.name}'s duration: ${entry.duration}`);
  });

  // Log entries with type "mark"
  perfEntries = list.getEntriesByType("mark");
  perfEntries.forEach((entry) => {
    console.log(`${entry.name}'s startTime: ${entry.startTime}`);
  });
});

// Subscribe to various performance event types
observer.observe({
  entryTypes: ["mark", "measure", "navigation", "resource"],
});
```

Specifications
--------------

| Specification |
| --- |
| Performance Timeline # dom-performanceobserverentrylist-getentriesbytype |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


TreeWalker: parentNode() method - Web APIs

TreeWalker: parentNode() method
===============================

 The **`TreeWalker.parentNode()`** method moves the current
 `Node` to the first *visible* ancestor node in the document order,
 and returns the found node. If no such node exists, or if it is above the
 `TreeWalker`'s *root node*, it returns `null` and the current
 node is not changed.

Syntax
------

```js
parentNode()
```

### Parameters

None.

### Return value

A `Node` object or `null`.

Examples
--------

```js
const treeWalker = document.createTreeWalker(
  document.body,
  NodeFilter.SHOW\_ELEMENT,
  {
    acceptNode(node) {
      return NodeFilter.FILTER\_ACCEPT;
    },
  },
  false,
);
const node = treeWalker.parentNode(); // returns null as there is no parent
```

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-treewalker-parentnode |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The `TreeWalker` interface it belongs to.


TreeWalker: previousNode() method - Web APIs

TreeWalker: previousNode() method
=================================

 The **`TreeWalker.previousNode()`** method moves the current
 `Node` to the previous *visible* node in the document order, and
 returns the found node. If no such node
 exists, or if it is before that the *root node* defined at the object
 construction, it returns `null` and the current node is not changed.

Syntax
------

```js
previousNode()
```

### Parameters

None.

### Return value

A `Node` object or `null`.

Examples
--------

```js
const treeWalker = document.createTreeWalker(
  document.body,
  NodeFilter.SHOW\_ELEMENT,
  {
    acceptNode(node) {
      return NodeFilter.FILTER\_ACCEPT;
    },
  },
  false,
);
const node = treeWalker.previousNode(); // returns null as there is no parent
```

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-treewalker-previousnode |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The `TreeWalker` interface it belongs to.


TreeWalker: firstChild() method - Web APIs

TreeWalker: firstChild() method
===============================

 The **`TreeWalker.firstChild()`** method moves the current
 `Node` to the first *visible* child of the current node, and returns
 the found child. If no such child exists, it returns `null` and the current node is not changed.

Syntax
------

```js
firstChild()
```

### Parameters

None.

### Return value

A `Node` object or `null`.

Examples
--------

```js
const treeWalker = document.createTreeWalker(
  document.body,
  NodeFilter.SHOW\_ELEMENT,
  {
    acceptNode(node) {
      return NodeFilter.FILTER\_ACCEPT;
    },
  },
  false,
);
const node = treeWalker.firstChild(); // returns the first child of the root element, or null if none
```

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-treewalker-firstchild |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The `TreeWalker` interface it belongs to.


TreeWalker: filter property - Web APIs

TreeWalker: filter property
===========================

 The **`TreeWalker.filter`** read-only property returns a
 `NodeFilter` that is the filtering object associated with the
 `TreeWalker`.

 When creating the `TreeWalker`, the filter object is passed in as the third
 parameter, and its method `acceptNode()` is called on every
 single node to determine whether or not to accept it.

Value
-----

A `NodeFilter` object.

Examples
--------

```js
const treeWalker = document.createTreeWalker(
  document.body,
  NodeFilter.SHOW\_ELEMENT,
  {
    acceptNode(node) {
      return NodeFilter.FILTER\_ACCEPT;
    },
  },
);
nodeFilter = treeWalker.filter; // document.body in this case
```

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-treewalker-filter |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The `TreeWalker` interface it belongs to.


TreeWalker: currentNode property - Web APIs

TreeWalker: currentNode property
================================

 The **`TreeWalker.currentNode`** property represents the
 `Node` which the `TreeWalker` is currently pointing at.

Value
-----

A `Node`.

Examples
--------

```js
const treeWalker = document.createTreeWalker(
  document.body,
  NodeFilter.SHOW\_ELEMENT,
  {
    acceptNode(node) {
      return NodeFilter.FILTER\_ACCEPT;
    },
  },
);
root = treeWalker.currentNode; // the root element as it is the first element!
```

Specifications
--------------

| Specification |
| --- |
| DOM Standard # ref-for-dom-treewalker-currentnode① |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The `TreeWalker` interface.


TreeWalker: whatToShow property - Web APIs

TreeWalker: whatToShow property
===============================

 The **`TreeWalker.whatToShow`** read-only property returns a
 bitmask that indicates the types of
 nodes to show. Non-matching nodes are skipped, but their
 children may be included, if relevant. The possible values are:

| Constant | Numerical value | Description |
| --- | --- | --- |
| `NodeFilter.SHOW_ALL` | `4294967295` (that is the max value of `unsigned long`) | Shows all nodes. |
| `NodeFilter.SHOW_ATTRIBUTE`
Deprecated
 | `2` |
 Shows attribute `Attr` nodes. This is meaningful
 only when creating a `TreeWalker` with an
 `Attr` node as its root; in this case, it means
 that the attribute node will appear in the first position of the
 iteration or traversal. Since attributes are never children of other
 nodes, they do not appear when traversing over the document tree.
  |
| `NodeFilter.SHOW_CDATA_SECTION`
Deprecated
 | `8` | Shows `CDATASection` nodes. |
| `NodeFilter.SHOW_COMMENT` | `128` | Shows `Comment` nodes. |
| `NodeFilter.SHOW_DOCUMENT` | `256` | Shows `Document` nodes. |
| `NodeFilter.SHOW_DOCUMENT_FRAGMENT` | `1024` | Shows `DocumentFragment` nodes. |
| `NodeFilter.SHOW_DOCUMENT_TYPE` | `512` | Shows `DocumentType` nodes. |
| `NodeFilter.SHOW_ELEMENT` | `1` | Shows `Element` nodes. |
| `NodeFilter.SHOW_ENTITY`
Deprecated
 | `32` | Legacy, no more used. |
| `NodeFilter.SHOW_ENTITY_REFERENCE`

Deprecated
 | `16` | Legacy, no more used. |
| `NodeFilter.SHOW_NOTATION`
Deprecated
 | `2048` | Legacy, no more used. |
| `NodeFilter.SHOW_PROCESSING_INSTRUCTION` | `64` | Shows `ProcessingInstruction` nodes. |
| `NodeFilter.SHOW_TEXT` | `4` | Shows `Text` nodes. |

Value
-----

A bitmask.

Examples
--------

```js
const treeWalker = document.createTreeWalker(
  document.body,
  NodeFilter.SHOW\_ELEMENT + NodeFilter.SHOW\_COMMENT + NodeFilter.SHOW\_TEXT,
  { acceptNode: (node) => NodeFilter.FILTER\_ACCEPT },
  false,
);
if (
  treeWalker.whatToShow === NodeFilter.SHOW\_ALL ||
  treeWalker.whatToShow % (NodeFilter.SHOW\_COMMENT \* 2) >=
    NodeFilter.SHOW\_COMMENT
) {
  // treeWalker will show comments
}
```

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-treewalker-whattoshow |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The `TreeWalker` interface.


TreeWalker: lastChild() method - Web APIs

TreeWalker: lastChild() method
==============================

 The **`TreeWalker.lastChild()`** method moves the current
 `Node` to the last *visible* child of the current node, and returns
 the found child. If no such child exists, it returns `null` and the current node is not changed.

Syntax
------

```js
lastChild()
```

### Parameters

None.

### Return value

A `Node` object or `null`.

Examples
--------

```js
const treeWalker = document.createTreeWalker(
  document.body,
  NodeFilter.SHOW\_ELEMENT,
  {
    acceptNode(node) {
      return NodeFilter.FILTER\_ACCEPT;
    },
  },
);
const node = treeWalker.lastChild(); // returns the last visible child of the root element
```

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-treewalker-lastchild |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The `TreeWalker` interface it belongs to.


TreeWalker: nextNode() method - Web APIs

TreeWalker: nextNode() method
=============================

 The **`TreeWalker.nextNode()`** method moves the current
 `Node` to the next *visible* node in the document order, and returns
 the found node. If no such node exists, it returns `null` and the current node is not changed.

Syntax
------

```js
nextNode()
```

### Parameters

None.

### Return value

A `Node` object or `null`.

Examples
--------

```js
const treeWalker = document.createTreeWalker(
  document.body,
  NodeFilter.SHOW\_ELEMENT,
  {
    acceptNode(node) {
      return NodeFilter.FILTER\_ACCEPT;
    },
  },
  false,
);
const node = treeWalker.nextNode(); // returns the first child of root, as it is the next node in document order
```

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-treewalker-nextnode |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The `TreeWalker` interface it belongs to.


TreeWalker: nextSibling() method - Web APIs

TreeWalker: nextSibling() method
================================

 The **`TreeWalker.nextSibling()`** method moves the current
 `Node` to its next sibling, if any, and returns the found sibling. If there
 is no such node, it returns `null` and the current node is not changed.

Syntax
------

```js
nextSibling()
```

### Parameters

None.

### Return value

A `Node` object or `null`.

Examples
--------

```js
const treeWalker = document.createTreeWalker(
  document.body,
  NodeFilter.SHOW\_ELEMENT,
  {
    acceptNode(node) {
      return NodeFilter.FILTER\_ACCEPT;
    },
  },
  false,
);
treeWalker.firstChild();
const node = treeWalker.nextSibling(); // returns null if the first child of the root element has no sibling
```

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-treewalker-nextsibling |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The `TreeWalker` interface it belongs to.


TreeWalker: previousSibling() method - Web APIs

TreeWalker: previousSibling() method
====================================

 The **`TreeWalker.previousSibling()`** method moves the current
 `Node` to its previous sibling, if any, and returns the found sibling. If
 there is no such node, it returns `null` and the current node is not changed.

Syntax
------

```js
previousSibling()
```

### Parameters

None.

### Return value

A `Node` object or `null`.

Examples
--------

```js
const treeWalker = document.createTreeWalker(
  document.body,
  NodeFilter.SHOW\_ELEMENT,
  {
    acceptNode(node) {
      return NodeFilter.FILTER\_ACCEPT;
    },
  },
  false,
);
const node = treeWalker.previousSibling(); // returns null as there is no previous sibling
```

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-treewalker-previoussibling |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The `TreeWalker` interface it belongs to.


TreeWalker: root property - Web APIs

TreeWalker: root property
=========================

 The **`TreeWalker.root`** read-only property returns the node
 that is the root of what the TreeWalker traverses.

Value
-----

A `Node` object.

Examples
--------

```js
const treeWalker = document.createTreeWalker(
  document.body,
  NodeFilter.SHOW\_ELEMENT,
  {
    acceptNode(node) {
      return NodeFilter.FILTER\_ACCEPT;
    },
  },
  false,
);
root = treeWalker.root; // document.body in this case
```

Specifications
--------------

| Specification |
| --- |
| DOM Standard # dom-treewalker-root |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The `TreeWalker` interface.


Using device orientation with 3D transforms - Web APIs

Using device orientation with 3D transforms
===========================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

This article provides tips on how to use device orientation information in tandem with CSS 3D transforms.

Using orientation to rotate an element
--------------------------------------

The easiest way to convert orientation data to a 3D transform is basically to use the `alpha`, `gamma`, and `beta` values as `rotateZ`, `rotateX` and `rotateY` values.

It is important to keep in mind, however, that the Device Orientation coordinate system is different from the CSS coordinate system. Namely, the former is right-handed and its Y axis is positive upwards, while the latter is a left-handed coordinate system whose Y axis is positive to the bottom. Furthermore, the Device Orientation angle rotations should always be done in a Z - X' - Y'' order that does not match the order of some CSS Transforms. These are some of the practical consequences of these differences:

* The order of angle rotations matters, so make sure the alpha, beta and gamma rotations are applied in this order.
* The `rotate3d()` CSS transformation, and the `DOMMatrixReadOnly.rotate()` and `DOMMatrix.rotateSelf()` functions apply angle rotations in a Z - Y' - X'' order, so it is not possible to apply the alpha, beta and gamma rotations in the right order with a single call to any of them. Instead, you should rotate each axis individually in the correct order.
* Due to the differences in coordinate systems outlined above, when looking towards the origin rotations are applied clockwise around in CSS and counter-clockwise in the Device Orientation spec. This means alpha and beta need to be inverted (the rotations around Z and X), because they point to different directions in the two coordinate systems. However, gamma (the rotation around Y) should be kept as is.
 Here is a code snippet to sum it up:

```js
const elem = document.getElementById("view3d");

window.addEventListener("deviceorientation", (e) => {
  elem.style.transform = `rotateZ(${-e.alpha}deg) rotateX(${-e.beta}deg) rotateY(${
 e.gamma
 }deg)`;
});
```

Convert from `rotate3d()` angles to `deviceorientation` angles
--------------------------------------------------------------

Should you ever need to convert a rotate3d axis-angle to orientation Euler angles, used by `deviceorientation`, you can use the following algorithm:

```js
// convert a rotate3d axis-angle to deviceorientation angles
function orient(aa) {
  const x = aa.x,
    y = aa.y,
    z = aa.z,
    a = aa.a,
    c = Math.cos(aa.a),
    s = Math.sin(aa.a),
    t = 1 - c,
    // axis-angle to rotation matrix
    rm00 = c + x \* x \* t,
    rm10 = z \* s + y \* x \* t,
    rm20 = -y \* s + z \* x \* t,
    rm01 = -z \* s + x \* y \* t,
    rm11 = c + y \* y \* t,
    rm21 = x \* s + z \* y \* t,
    rm02 = y \* s + x \* z \* t,
    rm12 = -x \* s + y \* z \* t,
    rm22 = c + z \* z \* t,
    TO\_DEG = 180 / Math.PI,
    ea = [],
    n = Math.hypot(rm22, rm20);

  // rotation matrix to Euler angles
  ea[1] = Math.atan2(-rm21, n);

  if (n > 0.001) {
    ea[0] = Math.atan2(rm01, rm11);
    ea[2] = Math.atan2(rm20, rm22);
  } else {
    ea[0] = 0;
    ea[2] = (rm21 > 0 ? 1 : -1) \* Math.atan2(-rm10, rm00);
  }

  return {
    alpha: -ea[0] \* TO\_DEG - 180,
    beta: -ea[1] \* TO\_DEG,
    gamma: ea[2] \* TO\_DEG,
  };
}
```

See also
--------

* Using CSS transforms
* Detecting device orientation


Detecting device orientation - Web APIs

Detecting device orientation
============================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

Increasingly, web-enabled devices are capable of determining their **orientation**; that is, they can report data indicating changes to their orientation with relation to the pull of gravity. In particular, hand-held devices such as mobile phones can use this information to automatically rotate the display to remain upright, presenting a wide-screen view of the web content when the device is rotated so that its width is greater than its height.

There are two JavaScript events that handle orientation information. The first one is the `DeviceOrientationEvent`, which is sent when the accelerometer detects a change to the orientation of the device. By receiving and processing the data reported by these orientation events, it's possible to interactively respond to rotation and elevation changes caused by the user moving the device.

The second event is the `DeviceMotionEvent`, which is sent when a change in acceleration was added. It is different from the `DeviceOrientationEvent` because it is listening for changes in acceleration as opposed to orientation. Sensors that are commonly capable of detecting `DeviceMotionEvent` include sensors in laptops to protect moving storage devices. `DeviceOrientationEvent` is more commonly found in mobile devices.

Processing orientation events
-----------------------------

All you need to do in order to begin receiving orientation change is to listen to the `deviceorientation` event:

```js
window.addEventListener("deviceorientation", handleOrientation, true);
```

After registering your event listener (in this case, a JavaScript function called `handleOrientation()`), your listener function periodically gets called with updated orientation data.

The orientation event contains four values:

* `DeviceOrientationEvent.absolute`
* `DeviceOrientationEvent.alpha`
* `DeviceOrientationEvent.beta`
* `DeviceOrientationEvent.gamma`

The event handler function can look something like this:

```js
function handleOrientation(event) {
  const absolute = event.absolute;
  const alpha = event.alpha;
  const beta = event.beta;
  const gamma = event.gamma;

  // Do stuff with the new orientation data
}
```

**Note:** parallax is a polyfill for normalizing the accelerometer and gyroscope data on mobile devices. This is useful for overcoming some of the differences in device support for device orientation.

### Orientation values explained

The value reported for each axis indicates the amount of rotation around a given axis in reference to a standard coordinate frame. These are described in greater detail in the Orientation and motion data explained article which is summarized below.

* The `DeviceOrientationEvent.alpha` value represents the motion of the device around the z axis, represented in degrees with values ranging from 0 (inclusive) to 360 (exclusive).
* The `DeviceOrientationEvent.beta` value represents the motion of the device around the x axis, represented in degrees with values ranging from -180 (inclusive) to 180 (exclusive). This represents a front to back motion of the device.
* The `DeviceOrientationEvent.gamma` value represents the motion of the device around the y axis, represented in degrees with values ranging from -90 (inclusive) to 90 (exclusive). This represents a left to right motion of the device.
### Orientation example

This example will work on any browser supporting the `deviceorientation` event and running on a device able to detect its orientation.

So let's imagine a ball in a garden:

```html
<div class="garden">
  <div class="ball"></div>
</div>
Hold the device parallel to the ground. Rotate along its x and y axes to see the
ball move up/down and left/right respectively.
<pre class="output"></pre>
```

This garden is 200 pixel wide (yes, it's a tiny one), and the ball is in the center:

```css
.garden {
  position: relative;
  width: 200px;
  height: 200px;
  border: 5px solid #ccc;
  border-radius: 10px;
}

.ball {
  position: absolute;
  top: 90px;
  left: 90px;
  width: 20px;
  height: 20px;
  background: green;
  border-radius: 100%;
}
```

Now, if we move our device, the ball will move accordingly:

```js
const ball = document.querySelector(".ball");
const garden = document.querySelector(".garden");
const output = document.querySelector(".output");

const maxX = garden.clientWidth - ball.clientWidth;
const maxY = garden.clientHeight - ball.clientHeight;

function handleOrientation(event) {
  let x = event.beta; // In degree in the range [-180,180)
  let y = event.gamma; // In degree in the range [-90,90)

  output.textContent = `beta: ${x}\n`;
  output.textContent += `gamma: ${y}\n`;

  // Because we don't want to have the device upside down
  // We constrain the x value to the range [-90,90]
  if (x > 90) {
    x = 90;
  }
  if (x < -90) {
    x = -90;
  }

  // To make computation easier we shift the range of
  // x and y to [0,180]
  x += 90;
  y += 90;

  // 10 is half the size of the ball
  // It centers the positioning point to the center of the ball
  ball.style.left = `${(maxY \* y) / 180 - 10}px`; // rotating device around the y axis moves the ball horizontally
  ball.style.top = `${(maxX \* x) / 180 - 10}px`; // rotating device around the x axis moves the ball vertically
}

window.addEventListener("deviceorientation", handleOrientation);
```

Click here to open this example in a new window; because `deviceorientation` doesn't work in a cross-origin `<iframe>` in all browsers.

Processing motion events
------------------------

Motion events are handled the same way as the orientation events except that they have their own event's name: `devicemotion`

```js
window.addEventListener("devicemotion", handleMotion, true);
```

What's really changed are the information provided within the `DeviceMotionEvent` object passed as a parameter of the event listener (`handleMotion()` in our example).

The motion event contains four properties:

* `DeviceMotionEvent.acceleration`
* `DeviceMotionEvent.accelerationIncludingGravity`
* `DeviceMotionEvent.rotationRate`
* `DeviceMotionEvent.interval`
### Motion values explained

The `DeviceMotionEvent` objects provide web developers with information about the speed of changes for the device's position and orientation. The changes are provided along three axis (see Orientation and motion data explained for details).

For `acceleration` and `accelerationIncludingGravity`, those axes correspond to the following:

`x`

Represents the axis from West to East

`y`

Represents the axis from South to North

`z`

Represents the axis perpendicular to the ground

For `rotationRate`, the situation is a bit different; the information corresponds to the following in each case:

`alpha`

Represents a rotation rate along the axis perpendicular to the screen (or keyboard for desktop).

`beta`

Represents a rotation rate along the axis going from left to right of the plane of the screen (or keyboard for desktop).

`gamma`

Represents a rotation rate along the axis going from bottom to top of the plane of the screen (or keyboard for desktop).

Finally, `interval` represents the interval of time, in milliseconds, at which data are obtained from the device.

Specifications
--------------

| Specification |
| --- |
| DeviceOrientation Event Specification # devicemotion |
| DeviceOrientation Event Specification # deviceorientation |

Browser compatibility
---------------------

### api.DeviceMotionEvent

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

### api.DeviceOrientationEvent

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `DeviceOrientationEvent`
* `DeviceMotionEvent`
* Orientation and motion data explained
* Using deviceorientation in 3D Transforms
* Cyber Orb: 2D maze game with device orientation