CSSNumericValue: equals() method - Web APIs

CSSNumericValue: equals() method
================================

 The **`equals()`** method of the
 `CSSNumericValue` interface returns a boolean indicating whether the passed
 value are strictly equal. To return a value of `true`, all passed values must
 be of the same type and value and must be in the same order. This allows structural
 equality to be tested quickly.

Syntax
------

```js
equals(number)
```

### Parameters

`number`

Either a number or a `CSSNumericValue`.

### Return value

A boolean value.

### Exceptions

None.

Examples
--------

 As stated earlier, all passed values must be of the same type and value and must be in
 the same order. Some of the following examples illustrate what happens when they are
 not.

```js
let cssMathSum = new CSSMathSum(CSS.px(1), CSS.px(2));
let matchingCssMathSum = new CSSMathSum(CSS.px(1), CSS.px(2));
// Prints true
console.log(cssMathSum.equals(matchingCssMathSum));

let otherCssMathSum = CSSMathSum(CSS.px(2), CSS.px(1));
// Prints false
console.log(cssMathSum.equals(otherCssMathSum));

// Also prints false
console.log(CSS.cm("1").equal(CSS.in("0.393701")));
```

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

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-cssnumericvalue-equals |

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

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


CSSNumericValue: type() method - Web APIs

CSSNumericValue: type() method
==============================

 The **`type()`** method of the
 `CSSNumericValue` interface returns the type of
 `CSSNumericValue`, one of `angle`, `flex`,
 `frequency`, `length`, `resolution`,
 `percent`, `percentHint`, or `time`.

Syntax
------

```js
type()
```

### Parameters

None.

### Return value

A `CSSNumericType` object.

### Exceptions

None.

Examples
--------

```js
let mathSum = CSS.px("23")
  .sub(CSS.percent("4"))
  .sub(CSS.cm("3"))
  .sub(CSS.in("9"));
// Returns an object with the structure: {length: 1, percentHint: "length"}
let cssNumericType = mathSum.type();
```

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

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-cssnumericvalue-type |

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

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


CSSNumericValue: toSum() method - Web APIs

CSSNumericValue: toSum() method
===============================

 The **`toSum()`** method of the
 `CSSNumericValue` interface converts the object's value to a
 `CSSMathSum` object to values of the specified unit.

Syntax
------

```js
toSum(units)
```

### Parameters

`units`

The units to convert to.

### Return value

A `CSSNumericValue`.

### Exceptions

`TypeError`

Thrown if an invalid type was passed to the method.

Examples
--------

```js
let v = CSS.px("23").add(CSS.percent("4")).add(CSS.cm("3")).add(CSS.in("9"));
v.toString(); // => "calc(23px + 4% + 3cm + 9in)"
v.toSum("px", "percent").toString(); // => "calc(1000.39px + 4%)"
```

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

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-cssnumericvalue-tosum |

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

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


CSSNumericValue: mul() method - Web APIs

CSSNumericValue: mul() method
=============================

 The **`mul()`** method of the
 `CSSNumericValue` interface multiplies the `CSSNumericValue` by
 the supplied value.

Syntax
------

```js
mul(number)
```

### Parameters

`number`

Either a number or a `CSSNumericValue`.

### Return value

A `CSSMathProduct`

### Exceptions

`TypeError`

Thrown if an invalid type was passed to the method.

Examples
--------

```js
let mathSum = CSS.px("23")
  .mul(CSS.percent("4"))
  .mul(CSS.cm("3"))
  .mul(CSS.in("9"));
// Prints "calc(23px \* 4% \* 3cm \* 9in)"
console.log(mathSum.toString());
```

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

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-cssnumericvalue-mul |

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

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


CSSNumericValue: parse() static method - Web APIs

CSSNumericValue: parse() static method
======================================

 The **`parse()`** static method of the
 `CSSNumericValue` interface converts a value string into an object whose
 members are value and the units.

Syntax
------

```js
CSSNumericValue.parse(cssText)
```

### Parameters

`cssText`

a string containing numeric and unit parts.

### Return value

A `CSSNumericValue`.

### Exceptions

`SyntaxError` `DOMException`

TBD

Examples
--------

 The following returns a `CSSUnitValue` object with a `unit`
 property equal to `"px"` and a `value` property equal to
 `42`.

```js
let numValue = CSSNumericValue.parse("42.0px");
```

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

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-cssnumericvalue-parse |

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

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


CSSNumericValue: sub() method - Web APIs

CSSNumericValue: sub() method
=============================

 The **`sub()`** method of the
 `CSSNumericValue` interface subtracts a supplied number from the
 `CSSNumericValue`.

Syntax
------

```js
sub(number)
```

### Parameters

`number`

Either a number or a `CSSMathSum`.

### Return value

A `CSSMathSum`

### Exceptions

`TypeError`

Thrown if an invalid type was passed to the method.

Examples
--------

```js
let mathSum = CSS.px("23")
  .sum(CSS.percent("4"))
  .sum(CSS.cm("3"))
  .sum(CSS.in("9"));
// Prints "calc(23px - 4% - 3cm - 9in)"
console.log(mathSum.toString());
```

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

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-cssnumericvalue-sub |

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

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


TextDecoder: encoding property - Web APIs

TextDecoder: encoding property
==============================

The **`TextDecoder.encoding`** read-only property returns a string containing the name of the decoding algorithm used by the specific decoder object.

The encoding is set by the constructor `label` parameter, and defaults to `utf-8`.

Value
-----

A lower-cased ASCII string, which can be one of the following values:

* The recommended encoding for the Web: `'utf-8'`.
* The legacy single-byte encodings:
 'ibm866',
 'iso-8859-2',
 'iso-8859-3',
 'iso-8859-4',
 'iso-8859-5',
 'iso-8859-6',
 'iso-8859-7',
 'iso-8859-8''`,
 'iso-8859-8i',
 'iso-8859-10',
 'iso-8859-13',
 'iso-8859-14',
 'iso-8859-15',
 'iso-8859-16',
 'koi8-r',
 'koi8-u',
 'macintosh',
 'windows-874',
 'windows-1250',
 'windows-1251',
 'windows-1252',
 'windows-1253',
 'windows-1254',
 'windows-1255',
 'windows-1256',
 'windows-1257',
 'windows-1258', or
 'x-mac-cyrillic'.
* The legacy multi-byte Chinese (simplified) encodings:
 'gbk',
 'gb18030'.
* The legacy multi-byte Chinese (traditional) encoding:
 'big5'.
* The legacy multi-byte Japanese encodings:
 'euc-jp',
 'iso-2022-jp',
 'shift-jis'.
* The legacy multi-byte Korean encodings:
 'euc-kr'.
* The legacy miscellaneous encodings:
 'utf-16be',
 'utf-16le',
 `'x-user-defined'`.
* A special encoding, `'replacement'`.
 This decodes empty input into empty output and any other arbitrary-length input into a single replacement character.
 It is used to prevent attacks that mismatch encodings between the client and server.
 The following encodings also map to the replacement encoding: `ISO-2022-CN`, `ISO-2022-CN-ext`, 'iso-2022-kr', and 'hz-gb-2312'.
Specifications
--------------

| Specification |
| --- |
| Encoding Standard # ref-for-dom-textdecoder-encoding① |

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

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

See also
--------

* The `TextDecoder` interface it belongs to.


TextDecoder: ignoreBOM property - Web APIs

TextDecoder: ignoreBOM property
===============================

The **`ignoreBOM`** read-only property of the `TextDecoder` interface is a `Boolean` indicating whether the byte order mark will be included in the output or skipped over.

Value
-----

`true` if the byte order mark will be included in the decoded text; `false` if it will be skipped over when decoding and omitted.

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

| Specification |
| --- |
| Encoding Standard # ref-for-dom-textdecoder-ignorebom① |

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

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


TextDecoder: TextDecoder() constructor - Web APIs

TextDecoder: TextDecoder() constructor
======================================

The **`TextDecoder()`** constructor returns a newly created `TextDecoder` object for the encoding specified in parameter.

Syntax
------

```js
new TextDecoder()
new TextDecoder(label)
new TextDecoder(label, options)
```

### Parameters

`label` Optional

 A string, defaulting to `"utf-8"`.
 This may be any valid label.

`options` Optional

An object with the following properties:

`fatal` Optional

 A boolean value indicating if the `TextDecoder.decode()` method must throw a `TypeError` when decoding invalid data.
 It defaults to `false`, which means that the decoder will substitute malformed data with a replacement character.

`ignoreBOM` Optional

 A boolean value indicating whether the byte order mark will be included in the output or skipped over.
 It defaults to `false`, which means that the byte order mark will be skipped over when decoding and will not be included in the decoded text.

### Exceptions

`RangeError`

Thrown if the value of `label` is unknown, or is one of the values leading to a `'replacement'` decoding algorithm (`"iso-2022-cn"` or `"iso-2022-cn-ext"`).

Examples
--------

```js
const textDecoder1 = new TextDecoder("iso-8859-2");
const textDecoder2 = new TextDecoder();
const textDecoder3 = new TextDecoder("csiso2022kr", { fatal: true }); // Allows TypeError exception to be thrown.
const textDecoder4 = new TextDecoder("iso-2022-cn"); // Throw a RangeError exception.
```

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

| Specification |
| --- |
| Encoding Standard # ref-for-dom-textdecoder① |

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

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

See also
--------

* The `TextDecoder` interface it belongs to.


TextDecoder: fatal property - Web APIs

TextDecoder: fatal property
===========================

The **`fatal`** read-only property of the `TextDecoder` interface is a `Boolean` indicating whether the error mode is fatal.

 If the property is `true`, then a decoder will throw a `TypeError` if it encounters malformed data while decoding.
 If `false`, the decoder will substitute the invalid data with the replacement character `U+FFFD` (�).
 The value of the property is set in the `TextDecoder()` constructor.

Value
-----

 A boolean which will be `true` if the error mode is set to `fatal`.
 Otherwise, it will be `false`, indicating that the error mode is `replacement`.

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

| Specification |
| --- |
| Encoding Standard # ref-for-dom-textdecoder-fatal① |

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

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


TextDecoder: decode() method - Web APIs

TextDecoder: decode() method
============================

The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter.

 The decoding method is defined in the current `TextDecoder` object.
 This includes the expected encoding of the data, and how decoding errors are handled.

Syntax
------

```js
decode()
decode(buffer)
decode(buffer, options)
```

### Parameters

`buffer` Optional

An `ArrayBuffer`, a `TypedArray`, or a `DataView` object containing the encoded text to decode.

`options` Optional

An object with the property:

`stream`

 A boolean flag indicating whether additional data will follow in subsequent calls to `decode()`.
 Set to `true` if processing the data in chunks, and `false` for the final chunk or if the data is not chunked.
 It defaults to `false`.

### Exceptions

`TypeError`

Thrown if there is a decoding error when the property `TextDecoder.fatal` is `true`.

### Return value

A string.

Examples
--------

This example encodes and decodes the euro symbol, €.

### HTML

```html
<p>Encoded value: <span id="encoded-value"></span></p>
<p>Decoded value: <span id="decoded-value"></span></p>
```

### JavaScript

```js
const encoder = new TextEncoder();
const array = encoder.encode("€"); // Uint8Array(3) [226, 130, 172]
document.getElementById("encoded-value").textContent = array;

const decoder = new TextDecoder();
const str = decoder.decode(array); // String "€"
document.getElementById("decoded-value").textContent = str;
```

### Result

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

| Specification |
| --- |
| Encoding Standard # ref-for-dom-textdecoder-decode① |

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

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

See also
--------

* The `TextDecoder` interface it belongs to.


MediaStreamTrackAudioSourceNode: MediaStreamTrackAudioSourceNode() constructor - Web APIs

MediaStreamTrackAudioSourceNode: MediaStreamTrackAudioSourceNode() constructor
==============================================================================

The Web Audio API's **`MediaStreamTrackAudioSourceNode()`** constructor creates and returns a new `MediaStreamTrackAudioSourceNode` object whose audio is taken from the `MediaStreamTrack` specified in the given options object.

Another way to create a `MediaStreamTrackAudioSourceNode` is to call the `AudioContext.createMediaStreamTrackSource()` method, specifying the `MediaStreamTrack` from which you want to obtain audio.

Syntax
------

```js
new MediaStreamTrackAudioSourceNode(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 `MediaStreamTrackAudioSourceNode` to have:

`mediaStreamTrack`

The `MediaStreamTrack` from which to take audio data for this node's output.

### Return value

A new `MediaStreamTrackAudioSourceNode` object representing the audio node whose media is obtained from the specified media track.

### Exceptions

`NotSupportedError` `DOMException`

Thrown if the specified `context` is not an `AudioContext`.

`InvalidStateError` `DOMException`

Thrown if the specified `MediaStreamTrack` isn't an audio track (that is, its `kind` property isn't `audio`.

Example
-------

This example uses `getUserMedia()` to obtain access to the user's camera, then creates a new `MediaStreamAudioSourceNode` from the first audio track provided by the device.

```js
const audioCtx = new AudioContext();

if (navigator.mediaDevices.getUserMedia) {
  navigator.mediaDevices
    .getUserMedia({
      audio: true,
      video: false,
    })
    .then((stream) => {
      const options = {
        mediaStreamTrack: stream.getAudioTracks()[0],
      };

      const source = new MediaStreamTrackAudioSourceNode(audioCtx, options);
      source.connect(audioCtx.destination);
    })
    .catch((err) => {
      console.error(`The following gUM error occurred: ${err}`);
    });
} else {
  console.log("new getUserMedia not supported on your browser!");
}
```

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

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

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

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


PasswordCredential: name property - Web APIs

PasswordCredential: name property
=================================

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

 The **`name`** read-only property of
 the `PasswordCredential` interface returns a string
 containing a human-readable public name for display in a credential chooser.

Value
-----

A string containing a name.

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

| Specification |
| --- |
| Credential Management Level 1 # dom-credentialuserdata-name |

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

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


PasswordCredential: PasswordCredential() constructor - Web APIs

PasswordCredential: PasswordCredential() constructor
====================================================

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

 The **`PasswordCredential()`**
 constructor creates a new `PasswordCredential` object. In
 supporting browsers, an instance of this class may be passed the `credential`
 from the `init` object for global `fetch()`.

Syntax
------

```js
new PasswordCredential(passwordCredentialData)
new PasswordCredential(htmlFormElement)
```

### Parameters

Either of the following:

`passwordCredentialData`

An object with the following properties:

`iconURL` Optional

The URL of a user's avatar image.

`id`

The ID of the user signing in.

`name` Optional

The name of the user signing in.

`password`

The password of the user signing in.

`htmlFormElement`

 A reference to an `HTMLFormElement` with appropriate input fields. The
 form should, at the very least, contain an id and password. It could also require a
 CSRF token.

Examples
--------

 This example shows how to set up an `HTMLFormElement` to capture data
 which we'll use to create a `PasswordCredential` object.

Starting with the form element.

```html
<form id="form" method="post">
  <label for="id">Username:</label>
  <input type="text" name="id" autocomplete="username" />
  <label for="password">Password:</label>
  <input type="password" name="password" autocomplete="current-password" />
  <input type="hidden" name="csrf\_token" value="\*\*\*\*\*" />
</form>
```

 Then, a reference to this form element, using it to create
 a `PasswordCredential` object, and storing it in the browser's password
 system.

```js
const form = document.querySelector("#form");
const creds = new PasswordCredential(form);
// Store the credentials.
navigator.credentials.store(creds).then((creds) => {
  // Do something with the credentials if you need to.
});
```

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

| Specification |
| --- |
| Credential Management Level 1 # dom-passwordcredential-passwordcredential |

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

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


PasswordCredential: password property - Web APIs

PasswordCredential: password property
=====================================

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

 The **`password`** read-only property
 of the `PasswordCredential` interface returns a string
 containing the password of the credential.

Value
-----

A string containing a password.

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

| Specification |
| --- |
| Credential Management Level 1 # dom-passwordcredential-password |

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

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


PasswordCredential: iconURL property - Web APIs

PasswordCredential: iconURL property
====================================

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

 The **`iconURL`** read-only property
 of the `PasswordCredential` interface returns a string
 containing a URL pointing to an image for an icon. This image is intended for display
 in a credential chooser. The URL must be accessible without authentication.

Value
-----

A string containing a URL.

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

| Specification |
| --- |
| Credential Management Level 1 # dom-credentialuserdata-iconurl |

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

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


BluetoothRemoteGATTCharacteristic: writeValueWithResponse() method - Web APIs

BluetoothRemoteGATTCharacteristic: writeValueWithResponse() method
==================================================================

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

The **`BluetoothRemoteGATTCharacteristic.writeValueWithResponse()`** method sets a `BluetoothRemoteGATTCharacteristic` object's `value` property to the bytes contained in a given `ArrayBuffer`, calls `WriteCharacteristicValue`(*this*=`this`, *value=value*, *response*=`"required"`), and returns the resulting `Promise`.

Syntax
------

```js
writeValueWithResponse(value)
```

### Parameters

`value`

An `ArrayBuffer`.

### Return value

A `Promise`.

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

| Specification |
| --- |
| Web Bluetooth # dom-bluetoothremotegattcharacteristic-writevaluewithresponse |

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

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


BluetoothRemoteGATTCharacteristic: getDescriptors() method - Web APIs

BluetoothRemoteGATTCharacteristic: getDescriptors() method
==========================================================

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

 The **`BluetoothRemoteGATTCharacteristic.getDescriptors()`** method
 returns a `Promise` that resolves to an `Array` of all
 `BluetoothRemoteGATTDescriptor` objects for a given descriptor UUID.

Syntax
------

```js
getDescriptors(bluetoothDescriptorUUID)
```

### Parameters

None.

### Return value

 A `Promise` that resolves to an `Array`
 of `BluetoothRemoteGATTDescriptor` objects.

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

| Specification |
| --- |
| Web Bluetooth # dom-bluetoothremotegattcharacteristic-getdescriptors |

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

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


BluetoothRemoteGATTCharacteristic: writeValue() method - Web APIs

BluetoothRemoteGATTCharacteristic: writeValue() method
======================================================

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

Use `BluetoothRemoteGATTCharacteristic.writeValueWithResponse()` and `BluetoothRemoteGATTCharacteristic.writeValueWithoutResponse()` instead.

The **`BluetoothRemoteGATTCharacteristic.writeValue()`** method sets a `BluetoothRemoteGATTCharacteristic` object's `value` property to the bytes contained in a given `ArrayBuffer`, calls `WriteCharacteristicValue`(*this*=`this`, *value=value*, *response*=`"optional"`), and returns the resulting `Promise`.

Syntax
------

```js
writeValue(value)
```

### Parameters

`value`

An `ArrayBuffer`.

### Return value

A `Promise`.

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

| Specification |
| --- |
| Web Bluetooth # dom-bluetoothremotegattcharacteristic-writevalue |

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

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


BluetoothRemoteGATTCharacteristic: uuid property - Web APIs

BluetoothRemoteGATTCharacteristic: uuid property
================================================

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

 The **`BluetoothRemoteGATTCharacteristic.uuid`** read-only
 property returns a string containing the UUID of the characteristic, for
 example `'00002a37-0000-1000-8000-00805f9b34fb'` for the Heart Rate
 Measurement characteristic.

Value
-----

A string.

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

| Specification |
| --- |
| Web Bluetooth # dom-bluetoothremotegattcharacteristic-uuid |

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

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


BluetoothRemoteGATTCharacteristic: writeValueWithoutResponse() method - Web APIs

BluetoothRemoteGATTCharacteristic: writeValueWithoutResponse() method
=====================================================================

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

The **`BluetoothRemoteGATTCharacteristic.writeValueWithoutResponse()`** method sets a `BluetoothRemoteGATTCharacteristic` object's `value` property to the bytes contained in a given `ArrayBuffer`, calls `WriteCharacteristicValue`(*this*=`this`, *value=value*, *response*=`"never"`), and returns the resulting `Promise`.

Syntax
------

```js
writeValueWithoutResponse(value)
```

### Parameters

`value`

An `ArrayBuffer`.

### Return value

A `Promise`.

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

| Specification |
| --- |
| Web Bluetooth # dom-bluetoothremotegattcharacteristic-writevaluewithoutresponse |

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

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


BluetoothRemoteGATTCharacteristic: properties property - Web APIs

BluetoothRemoteGATTCharacteristic: properties property
======================================================

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

 The **`BluetoothRemoteGATTCharacteristic.properties`**
 read-only property returns a `BluetoothCharacteristicProperties` instance
 containing the properties of this characteristic.

Value
-----

The properties of this characteristic.

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

| Specification |
| --- |
| Web Bluetooth # dom-bluetoothremotegattcharacteristic-properties |

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

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


BluetoothRemoteGATTCharacteristic: readValue() method - Web APIs

BluetoothRemoteGATTCharacteristic: readValue() method
=====================================================

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

 The **`BluetoothRemoteGATTCharacteristic.readValue()`** method
 returns a `Promise` that resolves to a `DataView` holding a
 duplicate of the `value` property if it is available and supported. Otherwise
 it throws an error.

Syntax
------

```js
readValue()
```

### Parameters

None.

### Return value

A `Promise` that resolves to an `DataView`.

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

| Specification |
| --- |
| Web Bluetooth # dom-bluetoothremotegattcharacteristic-readvalue |

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

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


BluetoothRemoteGATTCharacteristic: service property - Web APIs

BluetoothRemoteGATTCharacteristic: service property
===================================================

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

 The **`BluetoothRemoteGATTCharacteristic.service`** read-only
 property returns the `BluetoothRemoteGATTService` this characteristic belongs to.

Value
-----

An instance `BluetoothRemoteGATTService`.

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

| Specification |
| --- |
| Web Bluetooth # dom-bluetoothremotegattcharacteristic-service |

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

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


BluetoothRemoteGATTCharacteristic: getDescriptor() method - Web APIs

BluetoothRemoteGATTCharacteristic: getDescriptor() method
=========================================================

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

 The **`BluetoothRemoteGATTCharacteristic.getDescriptor()`** method
 returns a `Promise` that resolves to the
 first `BluetoothRemoteGATTDescriptor` for a given descriptor UUID.

Syntax
------

```js
getDescriptor(bluetoothDescriptorUUID)
```

### Parameters

None.

### Return value

 A `Promise` that resolves to the
 first `BluetoothRemoteGATTDescriptor`.

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

| Specification |
| --- |
| Web Bluetooth # dom-bluetoothremotegattcharacteristic-getdescriptor |

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

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


BluetoothRemoteGATTCharacteristic: stopNotifications() method - Web APIs

BluetoothRemoteGATTCharacteristic: stopNotifications() method
=============================================================

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

 The **`BluetoothRemoteGATTCharacteristic.stopNotifications()`** method
 returns a `Promise` to the BluetoothRemoteGATTCharacteristic instance when
 there is no longer an active notification on it.

Syntax
------

```js
stopNotifications()
```

### Parameters

None.

### Return value

A `Promise`.

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

| Specification |
| --- |
| Web Bluetooth # dom-bluetoothremotegattcharacteristic-stopnotifications |

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

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


BluetoothRemoteGATTCharacteristic: startNotifications() method - Web APIs

BluetoothRemoteGATTCharacteristic: startNotifications() method
==============================================================

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

 The **`BluetoothRemoteGATTCharacteristic.startNotifications()`** method
 returns a `Promise` to the BluetoothRemoteGATTCharacteristic instance when
 there is an active notification on it.

Syntax
------

```js
startNotifications()
```

### Parameters

None.

### Return value

A `Promise` to the BluetoothRemoteGATTCharacteristic instance.

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

| Specification |
| --- |
| Web Bluetooth # dom-bluetoothremotegattcharacteristic-startnotifications |

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

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


BluetoothRemoteGATTCharacteristic: value property - Web APIs

BluetoothRemoteGATTCharacteristic: value property
=================================================

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

 The **`BluetoothRemoteGATTCharacteristic.value`** read-only
 property returns currently cached characteristic value. This value gets updated when the
 value of the characteristic is read or updated via a notification or indication.

Value
-----

The currently cached characteristic value.

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

| Specification |
| --- |
| Web Bluetooth # dom-bluetoothremotegattcharacteristic-value |

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

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


EncodedVideoChunk: byteLength property - Web APIs

EncodedVideoChunk: byteLength property
======================================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
The **`byteLength`** read-only property of the `EncodedVideoChunk` interface returns the length in bytes of the encoded video data.

Value
-----

An integer.

Examples
--------

In the following example the `byteLength` is printed to the console.

```js
const init = {
  type: "key",
  data: videoBuffer,
  timestamp: 23000000,
  duration: 2000000,
};
chunk = EncodedVideoChunk(init);

console.log(chunk.byteLength); //352800
```

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

| Specification |
| --- |
| WebCodecs # dom-encodedvideochunk-bytelength |

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

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


EncodedVideoChunk: type property - Web APIs

EncodedVideoChunk: type property
================================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
The **`type`** read-only property of the `EncodedVideoChunk` interface returns a value indicating whether the video chunk is a key chunk, which does not rely on other frames for decoding.

Value
-----

A string, one of:

`"key"`

The data is a key chunk.

`"delta"`

The data is not a key chunk.

Examples
--------

In the following example the `type` is printed to the console.

```js
const init = {
  type: "key",
  data: videoBuffer,
  timestamp: 23000000,
  duration: 2000000,
};
chunk = EncodedVideoChunk(init);

console.log(chunk.type); //"key"
```

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

| Specification |
| --- |
| WebCodecs # dom-encodedvideochunk-type |

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

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


EncodedVideoChunk: EncodedVideoChunk() constructor - Web APIs

EncodedVideoChunk: EncodedVideoChunk() constructor
==================================================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
The **`EncodedVideoChunk()`** constructor creates a new `EncodedVideoChunk` object representing a chunk of encoded video.

Syntax
------

```js
new EncodedVideoChunk(options)
```

### Parameters

`options`

An object containing the following members:

`type`

Indicates if the chunk is a key chunk that does not rely on other frames for encoding. One of:

`"key"`

The data is a key chunk.

`"delta"`

The data is not a key chunk.

`timestamp`

An integer representing the timestamp of the video in microseconds.

`duration`

An integer representing the length of the video in microseconds.

`data`

An `ArrayBuffer`, a `TypedArray`, or a `DataView` containing the video data.

`transfer`

An array of `ArrayBuffer`s that `EncodedVideoChunk` will detach and take ownership of. If the array contains the `ArrayBuffer` backing `data`, `EncodedVideoChunk` will use that buffer directly instead of copying from it.

Examples
--------

In the following example a new `EncodedVideoChunk` is created.

```js
const init = {
  type: "key",
  data: videoBuffer,
  timestamp: 23000000,
  duration: 2000000,
  transfer: [videoBuffer],
};
chunk = new EncodedVideoChunk(init);
```

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

| Specification |
| --- |
| WebCodecs # dom-encodedvideochunk-encodedvideochunk |

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

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


EncodedVideoChunk: timestamp property - Web APIs

EncodedVideoChunk: timestamp property
=====================================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
The **`timestamp`** read-only property of the `EncodedVideoChunk` interface returns an integer indicating the timestamp of the video in microseconds.

Value
-----

An integer.

Examples
--------

In the following example the `timestamp` is printed to the console.

```js
const init = {
  type: "key",
  data: videoBuffer,
  timestamp: 23000000,
  duration: 2000000,
};
chunk = EncodedVideoChunk(init);
console.log(chunk.timestamp); //23000000
```

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

| Specification |
| --- |
| WebCodecs # dom-encodedvideochunk-timestamp |

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

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


EncodedVideoChunk: duration property - Web APIs

EncodedVideoChunk: duration property
====================================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
The **`duration`** read-only property of the `EncodedVideoChunk` interface returns an integer indicating the duration of the video in microseconds.

Value
-----

An integer.

Examples
--------

In the following example the `duration` is printed to the console.

```js
const init = {
  type: "key",
  data: videoBuffer,
  timestamp: 23000000,
  duration: 2000000,
};
chunk = EncodedVideoChunk(init);

console.log(chunk.duration); //2000000
```

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

| Specification |
| --- |
| WebCodecs # dom-encodedvideochunk-duration |

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

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


EncodedVideoChunk: copyTo() method - Web APIs

EncodedVideoChunk: copyTo() method
==================================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
The **`copyTo()`** method of the `EncodedVideoChunk` interface copies the encoded chunk of video data.

Syntax
------

```js
copyTo(destination)
```

### Parameters

`destination`

An `ArrayBuffer`, a `TypedArray`, or a `DataView` that the data can be copied to.

### Return value

None (`undefined`).

Examples
--------

In the following example an `EncodedVideoChunk` is created then copied.

```js
const init = {
  type: "key",
  data: videoBuffer,
  timestamp: 23000000,
  duration: 2000000,
};
chunk = EncodedVideoChunk(init);

chunk.copyTo(newBuffer);
```

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

| Specification |
| --- |
| WebCodecs # dom-encodedvideochunk-copyto |

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

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


HIDInputReportEvent: data property - Web APIs

HIDInputReportEvent: data property
==================================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
**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 **`data`** property of the `HIDInputReportEvent` interface returns a `DataView` containing the data from the input report, excluding the `reportId` if the HID interface uses report IDs.

Value
-----

A `DataView`.

Examples
--------

In the following example the returned `data` is logged to the console.

```js
device.addEventListener("inputreport", (event) => {
  const { data, device, reportId } = event;
  console.log(data);
});
```

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

| Specification |
| --- |
| WebHID API # dom-hidinputreportevent-data |

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

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


HIDInputReportEvent: reportId property - Web APIs

HIDInputReportEvent: reportId property
======================================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
**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 **`reportId`** property of the `HIDInputReportEvent` interface returns the one-byte identification prefix for this report, or 0 if the HID interface does not use report IDs.

Value
-----

A one-byte identification prefix.

Examples
--------

In the following example the `reportId` of an incoming input report is logged to the console.

```js
device.addEventListener("inputreport", (event) => {
  const { data, device, reportId } = event;
  console.log(reportId);
});
```

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

| Specification |
| --- |
| WebHID API # dom-hidinputreportevent-reportid |

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

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


HIDInputReportEvent: device property - Web APIs

HIDInputReportEvent: device property
====================================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
**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 **`device`** property of the `HIDInputReportEvent` interface returns the `HIDDevice` instance that represents the HID interface that sent the input report.

Value
-----

An `HIDDevice`.

Examples
--------

In the following example `device` is a `HIDDevice` instance, representing the device sending the report. The `productName` of this device is logged to the console.

```js
device.addEventListener("inputreport", (event) => {
  const { data, device, reportId } = event;
  console.log(device.productName);
});
```

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

| Specification |
| --- |
| WebHID API # dom-hidinputreportevent-device |

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

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


Using the Popover API - Web APIs

Using the Popover API
=====================

The **Popover API** provides developers with a standard, consistent, flexible mechanism for displaying popover content on top of other page content. Popover content can be controlled either declaratively using HTML attributes, or via JavaScript. This article provides a detailed guide to using all of its features.

Creating declarative popovers
-----------------------------

In its simplest form, a popover is created by adding the `popover` attribute to the element that you want to contain your popover content. An `id` is also needed to associate the popover with its controls.

```html
<div id="mypopover" popover>Popover content</div>
```

**Note:** Setting the `popover` attribute with no value is equivalent to setting `popover="auto"`.

Adding this attribute causes the element to be hidden on page load by having `display: none` set on it. To show/hide the popover, you need to add some control buttons. You can set a `<button>` (or `<input>` of `type="button"`) as a popover control button by giving it a `popovertarget` attribute, the value of which should be the ID of the popover to control:

```html
<button popovertarget="mypopover">Toggle the popover</button>
<div id="mypopover" popover>Popover content</div>
```

The default behavior is for the button to be a toggle button — pressing it repeatedly will toggle the popover between showing and hidden.

If you want to change that behavior, you can use the `popovertargetaction` attribute — this takes a value of `"hide"`, `"show"`, or `"toggle"`. For example, to create separate show and hide buttons, you could do this:

```html
<button popovertarget="mypopover" popovertargetaction="show">
  Show popover
</button>
<button popovertarget="mypopover" popovertargetaction="hide">
  Hide popover
</button>
<div id="mypopover" popover>Popover content</div>
```

You can see how the previous code snippet renders in our Basic declarative popover example (source).

**Note:** If the `popovertargetaction` attribute is omitted, `"toggle"` is the default action that will be performed by a control button.

When a popover is shown, it has `display: none` removed from it and it is put into the top layer so it will sit on top of all other page content.

auto state, and "light dismiss"
-------------------------------

When a popover element is set with `popover` or `popover="auto"` as shown above, it is said to have **auto state**. The two important behaviors to note about auto state are:

* The popover can be "light dismissed" — this means that you can hide the popover by clicking outside it.
* The popover can also be closed, using browser-specific mechanisms such as pressing the `Esc` key.
* Usually, only one popover can be shown at a time — showing a second popover when one is already shown will hide the first one. The exception to this rule is when you have nested auto popovers. See the Nested popovers section for more details.

**Note:** `popover="auto"` popovers are also dismissed by successful `HTMLDialogElement.showModal()` and `Element.requestFullscreen()` calls on other elements in the document. Bear in mind however that calling these methods on a shown popover will result in failure because those behaviors don't make sense on an already-shown popover. You can however call them on an element with the `popover` attribute that isn't currently being shown.

Auto state is useful when you only want to show a single popover at once. Perhaps you have multiple teaching UI messages that you want to show, but don't want the display to start getting cluttered and confusing, or perhaps you are showing status messages where the new status overrides any previous status.

You can see the behavior described above in action in our Multiple auto popovers example (source). Try light dismissing the popovers after they are shown, and see what happens when you try to show both at the same time.

Using manual popover state
--------------------------

The alternative to auto state is **manual state**, achieved by setting `popover="manual"` on your popover element:

```html
<div id="mypopover" popover="manual">Popover content</div>
```

In this state:

* The popover cannot be "light dismissed", although declarative show/hide/toggle buttons (as seen earlier) will still work.
* Multiple independent popovers can be shown at a time.

You can see this behavior in action in our Multiple manual popovers example (source).

Showing popovers via JavaScript
-------------------------------

You can also control popovers using a JavaScript API.

The `HTMLElement.popover` property can be used to get or set the `popover` attribute. This can be used to create a popover via JavaScript, and is also useful for feature detection. For example:

```js
function supportsPopover() {
  return HTMLElement.prototype.hasOwnProperty("popover");
}
```

Similarly:

* `HTMLButtonElement.popoverTargetElement` and `HTMLInputElement.popoverTargetElement` provide an equivalent to the `popovertarget` attribute, allowing you to set up the control button(s) for a popover, although the property value taken is a reference to the popover DOM element to control.
* `HTMLButtonElement.popoverTargetAction` and `HTMLInputElement.popoverTargetAction` provide an equivalent to the `popovertargetaction` global HTML attribute, allowing you to specify the action taken by a control button.

Putting these three together, you can programmatically set up a popover and its control button, like so:

```js
const popover = document.getElementById("mypopover");
const toggleBtn = document.getElementById("toggleBtn");

const keyboardHelpPara = document.getElementById("keyboard-help-para");

const popoverSupported = supportsPopover();

if (popoverSupported) {
  popover.popover = "auto";
  toggleBtn.popoverTargetElement = popover;
  toggleBtn.popoverTargetAction = "toggle";
} else {
  toggleBtn.style.display = "none";
}
```

You also have several methods to control showing and hiding:

* `HTMLElement.showPopover()` to show a popover.
* `HTMLElement.hidePopover()` to hide a popover.
* `HTMLElement.togglePopover()` to toggle a popover.

For example, you might want to provide the ability to toggle a help popover on and off by clicking a button or pressing a particular key on the keyboard. The first one could be achieved declaratively, or you could do it using JavaScript as shown above.

For the second one, you could create an event handler that programs two separate keys — one to open the popover and one to close it again:

```js
document.addEventListener("keydown", (event) => {
  if (event.key === "h") {
    if (popover.matches(":popover-open")) {
      popover.hidePopover();
    }
  }

  if (event.key === "s") {
    if (!popover.matches(":popover-open")) {
      popover.showPopover();
    }
  }
});
```

This example uses `Element.matches()` to programmatically check whether a popover is currently showing. The `:popover-open` pseudo-class matches only popovers that are currently being shown. This is important to avoid the errors that are thrown if you try to show an already-shown popover, or hide an already-hidden popover.

Alternatively, you could program a single key to show *and* hide the popover like this:

```js
document.addEventListener("keydown", (event) => {
  if (event.key === "h") {
    popover.togglePopover();
  }
});
```

See our Toggle help UI example (source) to see the popover JavaScript properties, feature detection, and `togglePopover()` method in action.

Dismissing popovers automatically via a timer
---------------------------------------------

Another common pattern in JavaScript is dismissing popovers automatically after a certain amount of time. You might for example want to create a system of "toast" notifications, where you have multiple actions underway at a time (for example multiple files uploading), and want to show a notification when each one succeeds or fails. For this you'll want to use manual popovers so you can show several at the same time, and use `setTimeout()` to remove them. A function for handling such popovers might look like so:

```js
function makeToast(result) {
  const popover = document.createElement("article");
  popover.popover = "manual";
  popover.classList.add("toast");
  popover.classList.add("newest");

  let msg;

  if (result === "success") {
    msg = "Action was successful!";
    popover.classList.add("success");
    successCount++;
  } else if (result === "failure") {
    msg = "Action failed!";
    popover.classList.add("failure");
    failCount++;
  } else {
    return;
  }

  popover.textContent = msg;
  document.body.appendChild(popover);
  popover.showPopover();

  updateCounter();

  setTimeout(() => {
    popover.hidePopover();
    popover.remove();
  }, 4000);
}
```

You can also use the `beforetoggle` event to perform a follow-up action when a popover shows or hides. In our example we execute a `moveToastsUp()` function to make the toasts all move up the screen to make way each time a new toast appears:

```js
popover.addEventListener("toggle", (event) => {
  if (event.newState === "open") {
    moveToastsUp();
  }
});

function moveToastsUp() {
  const toasts = document.querySelectorAll(".toast");

  toasts.forEach((toast) => {
    if (toast.classList.contains("newest")) {
      toast.style.bottom = `5px`;
      toast.classList.remove("newest");
    } else {
      const prevValue = toast.style.bottom.replace("px", "");
      const newValue = parseInt(prevValue) + 50;
      toast.style.bottom = `${newValue}px`;
    }
  });
}
```

See our Toast popover example (source) to see the above example snippets in action, and full comments for explanation.

Nested popovers
---------------

There is an exception to the rule about not displaying multiple auto popovers at once — when they are nested inside one another. In such cases, multiple popovers are allowed to both be open at the same time, due to their relationship with each other. This pattern is supported to enable use cases such as nested popover menus.

There are three different ways to create nested popovers:

1. Direct DOM descendants:

```html
<div popover>
  Parent
  <div popover>Child</div>
</div>
```

2. Via invoking/control elements:

```html
<div popover>
  Parent
  <button popovertarget="foo">Click me</button>
</div>

<div popover id="foo">Child</div>
```

3. Via the `anchor` attribute:

```html
<div popover id="foo">Parent</div>

<div popover anchor="foo">Child</div>
```

See our Nested popover menu example (source) for an example. You'll notice that quite a few event handlers have been used to display and hide the subpopover appropriately during mouse and keyboard access, and also to hide both menus when an option is selected from either. Depending on how you handle loading of new content , either in an SPA or multi-page website, some of all of these may not be necessary, but they have been included in this demo for illustrative purposes.

Styling popovers
----------------

The popover API has some related CSS features available that are worth looking at.

In terms of styling the actual popover, you can select all popovers with a simple attribute selector (`[popover]`), or you select popovers that are showing using a new pseudo-class — `:popover-open`.

When looking at the first couple of examples linked at the start of the article, you may have noticed that the popovers appear in the middle of the viewport. This is the default styling, achieved like this in the UA stylesheet:

```css
[popover] {
  position: fixed;
  inset: 0;
  width: fit-content;
  height: fit-content;
  margin: auto;
  border: solid;
  padding: 0.25em;
  overflow: auto;
  color: CanvasText;
  background-color: Canvas;
}
```

To override the default styles and get the popover to appear somewhere else on your viewport, you would need to override the above styles with something like this:

```css
:popover-open {
  width: 200px;
  height: 100px;
  position: absolute;
  inset: unset;
  bottom: 5px;
  right: 5px;
  margin: 0;
}
```

You can see an isolated example of this in our Popover positioning example (source).

The `::backdrop` pseudo-element is a full-screen element placed directly behind showing popover elements in the top layer, allowing effects to be added to the page content behind the popover(s) if desired. You might for example want to blur out the content behind the popover to help focus the user's attention on it:

```css
::backdrop {
  backdrop-filter: blur(3px);
}
```

See our Popover blur background example (source) for an idea of how this renders.

Animating popovers
------------------

Popovers are set to `display: none;` when hidden and `display: block;` when shown, as well as being removed from / added to the top layer and the accessibility tree. Therefore, for popovers to be animated, the `display` property needs to be animatable. Supporting browsers animate `display` with a variation on the discrete animation type. Specifically, the browser will flip between `none` and another value of `display` so that the animated content is shown for the entire animation duration. So, for example:

* When animating `display` from `none` to `block` (or another visible `display` value), the value will flip to `block` at `0%` of the animation duration so it is visible throughout.
* When animating `display` from `block` (or another visible `display` value) to `none`, the value will flip to `none` at `100%` of the animation duration so it is visible throughout.

**Note:** When animating using CSS transitions, `transition-behavior: allow-discrete` needs to be set to enable the above behavior. When animating with CSS animations, the above behavior is available by default; an equivalent step is not required.

### Transitioning a popover

When animating popovers with CSS transitions, the following features are required:

`@starting-style` at-rule

Provides a set of starting values for properties set on the popover that you want to transition from when it is first shown. This is needed to avoid unexpected behavior. By default, CSS transitions only occur when a property changes from one value to another on a visible element; they are not triggered on an element's first style update, or when the `display` type changes from `none` to another type.

`display` property

Add `display` to the transitions list so that the popover will remain as `display: block` (or another visible `display` value) for the duration of the transition, ensuring the other transitions are visible.

`overlay` property

Include `overlay` in the transitions list to ensure the removal of the popover from the top layer is deferred until the transition completes, again ensuring the transition is visible.

`transition-behavior` property

Set `transition-behavior: allow-discrete` on the `display` and `overlay` transitions (or on the `transition` shorthand) to enable discrete transitions on these two properties that are not by default animatable.

Let's have a look at an example so you can see what this looks like:

#### HTML

The HTML contains a `<div>` element declared to be a popover via the global `popover` HTML attribute, and a `<button>` element designated as the popover's display control:

```html
<button popovertarget="mypopover">Show the popover</button>
<div popover="auto" id="mypopover">I'm a Popover! I should animate.</div>
```

#### CSS

The two popover properties we want to transition are `opacity` and `transform`. We want the popover to fade in or out while growing or shrinking horizontally. To achieve this, we set a starting state for these properties on the hidden state of the popover element (selected with the `[popover]` attribute selector) and an end state for the shown state of the popover (selected via the `:popover-open` pseudo-class). We also use the `transition` property to define the properties to animate and the animation's duration as the popover gets shown or hidden.

```css
html {
  font-family: Arial, Helvetica, sans-serif;
}

/\* Transition for the popover itself \*/

[popover]:popover-open {
  opacity: 1;
  transform: scaleX(1);
}

[popover] {
  font-size: 1.2rem;
  padding: 10px;

  /\* Final state of the exit animation \*/
  opacity: 0;
  transform: scaleX(0);

  transition:
    opacity 0.7s,
    transform 0.7s,
    overlay 0.7s allow-discrete,
    display 0.7s allow-discrete;
  /\* Equivalent to
 transition: all 0.7s allow-discrete; \*/
}

/\* Needs to be after the previous [popover]:popover-open rule
to take effect, as the specificity is the same \*/
@starting-style {
  [popover]:popover-open {
    opacity: 0;
    transform: scaleX(0);
  }
}

/\* Transition for the popover's backdrop \*/

[popover]::backdrop {
  background-color: rgb(0 0 0 / 0%);
  transition:
    display 0.7s allow-discrete,
    overlay 0.7s allow-discrete,
    background-color 0.7s;
  /\* Equivalent to
 transition: all 0.7s allow-discrete; \*/
}

[popover]:popover-open::backdrop {
  background-color: rgb(0 0 0 / 25%);
}

/\* The nesting selector (&) cannot represent pseudo-elements
so this starting-style rule cannot be nested \*/

@starting-style {
  [popover]:popover-open::backdrop {
    background-color: rgb(0 0 0 / 0%);
  }
}
```

As discussed earlier, we have also:

* Set a starting state for the `transition` inside the `@starting-style` block.
* Added `display` to the list of transitioned properties so that the animated element is visible (set to `display: block`) throughout the popover's entry and exit animations. Without this, the exit animation would not be visible; in effect, the popover would just disappear.
* Added `overlay` to the list of transitioned properties to make sure that the removal of the element from the top layer is deferred until the animation has been completed. The effect of this may not be noticeable for basic animations such as this one, but in more complex cases, omitting this property can result in the element being removed from the overlay before the transition completes.
* Set `allow-discrete` on both properties in the above transitions to enable discrete transitions.

You'll note that we've also included a transition on the `::backdrop` appearing behind the popover when it opens, providing a nice darkening animation.

#### Result

The code renders as follows:

**Note:** Because popovers change from `display: none` to `display: block` each time they are shown, the popover transitions from its `@starting-style` styles to its `[popover]:popover-open` styles every time the entry transition occurs. When the popover closes, it transitions from its `[popover]:popover-open` state to the default `[popover]` state.

It is possible for the style transition on entry and exit to be different in such cases. See our Demonstration of when starting styles are used example for a proof of this.

### A popover keyframe animation

When animating a popover with CSS keyframe animations, there are some differences to note:

* You don't provide a `@starting-style`; you include your "to" and "from" `display` values in keyframes.
* You don't explicitly enable discrete animations; there is no equivalent to `allow-discrete` inside keyframes.
* You don't need to set `overlay` inside keyframes either; the `display` animation handles the animation of the popover from shown to hidden.

Let's look at an example.

#### HTML

The HTML contains a `<div>` element declared as a popover, and a `<button>` element designated as the popover's display control:

```html
<button popovertarget="mypopover">Show the popover</button>
<div popover="auto" id="mypopover">I'm a Popover! I should animate.</div>
```

#### CSS

We have defined keyframes that specify the desired entry and exit animations, and an entry animation for the backdrop only. Note that it wasn't possible to animate the backdrop fade out — the backdrop is immediately removed from the DOM when the popover is closed, so there is nothing to animate.

```css
html {
  font-family: Arial, Helvetica, sans-serif;
}

[popover] {
  font-size: 1.2rem;
  padding: 10px;
  animation: fade-out 0.7s ease-out;
}

[popover]:popover-open {
  animation: fade-in 0.7s ease-out;
}

[popover]:popover-open::backdrop {
  animation: backdrop-fade-in 0.7s ease-out forwards;
}

/\* Animation keyframes \*/

@keyframes fade-in {
  0% {
    opacity: 0;
    transform: scaleX(0);
  }

  100% {
    opacity: 1;
    transform: scaleX(1);
  }
}

@keyframes fade-out {
  0% {
    opacity: 1;
    transform: scaleX(1);
    /\* display needed on the closing animation to keep the popover
 visible until the animation ends \*/
    display: block;
  }

  100% {
    opacity: 0;
    transform: scaleX(0);
    /\* display: none not required here because it is the default value
 for a closed popover, but including it so the behavior is clear \*/
    display: none;
  }
}

@keyframes backdrop-fade-in {
  0% {
    background-color: rgb(0 0 0 / 0%);
  }

  100% {
    background-color: rgb(0 0 0 / 25%);
  }
}
```

#### Result

The code renders as follows:


SpeechGrammar: weight property - Web APIs

SpeechGrammar: weight property
==============================

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

 The optional **`weight`** property of the
 `SpeechGrammar` interface sets and returns the weight of the
 `SpeechGrammar` object.

Value
-----

A float representing the weight of the grammar, in the range 0.0–1.0.

Examples
--------

```js
const grammar =
  "#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;";
const recognition = new SpeechRecognition();
const speechRecognitionList = new SpeechGrammarList();
speechRecognitionList.addFromString(grammar, 1);
recognition.grammars = speechRecognitionList;

console.log(speechRecognitionList[0].src); // should return the same as the contents of the grammar variable
console.log(speechRecognitionList[0].weight); // should return 1 - the same as the weight set in line 4.
```

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

| Specification |
| --- |
| Web Speech API # dom-speechgrammar-weight |

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

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

See also
--------

* Web Speech API


SpeechGrammar: SpeechGrammar() constructor - Web APIs

SpeechGrammar: SpeechGrammar() constructor
==========================================

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

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

 The **`SpeechGrammar()`** constructor of the
 `SpeechGrammar` interface creates a new `SpeechGrammar` object
 instance.

Syntax
------

```js
new SpeechGrammar()
```

### Parameters

None.

Examples
--------

```js
const grammar =
  "#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;";
const recognition = new SpeechRecognition();
const speechRecognitionList = new SpeechGrammarList();
speechRecognitionList.addFromString(grammar, 1);
recognition.grammars = speechRecognitionList;

const newGrammar = new SpeechGrammar();
newGrammar.src =
  "#JSGF V1.0; grammar names; public <name> = chris | kirsty | mike;";
speechRecognitionList[1] = newGrammar; // should add the new SpeechGrammar object to the list
```

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

This API has no official W3C or WHATWG specification.

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

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

See also
--------

* Web Speech API


SpeechGrammar: src property - Web APIs

SpeechGrammar: src property
===========================

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

 The **`src`** property of the `SpeechGrammar`
 interface sets and returns a string containing the grammar from within in the
 `SpeechGrammar` object.

Value
-----

A string representing the grammar.

Examples
--------

```js
const grammar =
  "#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;";
const recognition = new SpeechRecognition();
const speechRecognitionList = new SpeechGrammarList();
speechRecognitionList.addFromString(grammar, 1);
recognition.grammars = speechRecognitionList;

console.log(speechRecognitionList[0].src); // should return the same as the contents of the grammar variable
console.log(speechRecognitionList[0].weight); // should return 1 - the same as the weight set in line 4.
```

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

| Specification |
| --- |
| Web Speech API # dom-speechgrammar-src |

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

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

See also
--------

* Web Speech API


TrustedTypePolicyFactory: isHTML() method - Web APIs

TrustedTypePolicyFactory: isHTML() method
=========================================

The **`isHTML()`** method of the `TrustedTypePolicyFactory` interface returns true if it is passed a valid `TrustedHTML` object.

**Note:** The purpose of the functions `isHTML()`, `isScript()`, and `isScriptURL()` is to check if the object is a valid TrustedType object, created by a configured policy.

Syntax
------

```js
isHTML(value)
```

### Parameters

`value`

A `TrustedHTML` object.

### Return value

A `boolean` that is true if the object is a valid `TrustedHTML` object.

Examples
--------

In the below example the constant `html` was created by a policy, and therefore `isHTML()` returns true. The second example is an attempt to fake an object, and the third is a string. Both of these will return false when passed to `isHTML()`.

```js
const html = policy.createHTML("<div>");
console.log(trustedTypes.isHTML(html)); // true;

const fake = Object.create(TrustedHTML.prototype);
console.log(trustedTypes.isHTML(fake)); // false

console.log(trustedTypes.isHTML("<div>plain string</div>")); // false
```

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

| Specification |
| --- |
| Trusted Types # dom-trustedtypepolicyfactory-ishtml |

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

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


TrustedTypePolicyFactory: emptyScript property - Web APIs

TrustedTypePolicyFactory: emptyScript property
==============================================

The **`emptyScript`** read-only property of the `TrustedTypePolicyFactory` interface returns a `TrustedScript` object containing an empty string.

This object can be used when the application requires an empty string to be inserted into an injection sink which is expecting a `TrustedScript` object.

Value
-----

A `TrustedScript` object.

Examples
--------

The specification explains that the `emptyScript` object can be used to detect support for dynamic code compilation.

Native Trusted Types implementations can support `eval(TrustedScript)`, therefore in the below example a native implementation will return false for `eval(trustedTypes.emptyScript)`. A polyfill will return a truthy object.

```js
const supportsTS = !eval(trustedTypes.emptyScript);
eval(supportsTS ? myTrustedScriptObj : myTrustedScriptObj.toString());
```

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

| Specification |
| --- |
| Trusted Types # dom-trustedtypepolicyfactory-emptyscript |

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

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


TrustedTypePolicyFactory: emptyHTML property - Web APIs

TrustedTypePolicyFactory: emptyHTML property
============================================

The **`emptyHTML`** read-only property of the `TrustedTypePolicyFactory` interface returns a `TrustedHTML` object containing an empty string.

This object can be used when the application requires an empty string to be inserted into an injection sink.

Value
-----

A `TrustedHTML` object.

Examples
--------

In the below example an empty string is to be inserted into the element. Therefore there is no need to create a policy, and the `emptyHTML` property can be used to insert the empty element when a Trusted Types object is expected.

```js
el.innerHTML = trustedTypes.emptyHTML;
```

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

| Specification |
| --- |
| Trusted Types # dom-trustedtypepolicyfactory-emptyhtml |

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

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


TrustedTypePolicyFactory: getPropertyType() method - Web APIs

TrustedTypePolicyFactory: getPropertyType() method
==================================================

The **`getPropertyType()`** method of the `TrustedTypePolicyFactory` interface allows web developers to check if a Trusted Type is required for an element's property.

Syntax
------

```js
getPropertyType(tagName, property)
getPropertyType(tagName, property, elementNS)
```

### Parameters

`tagName`

A string containing the name of an HTML tag.

`property`

A string containing a property, for example `"innerHTML"`.

`elementNS` Optional

A string containing a namespace, if empty defaults to the HTML namespace.

### Return value

A string with one of:

* `"TrustedHTML"`
* `"TrustedScript"`
* `"TrustedScriptURL"`

Or, null.

Examples
--------

In this example, passing the `<div>` element and `innerHTML` property to `getPropertyType` returns "TrustedHTML".

```js
console.log(trustedTypes.getPropertyType("div", "innerHTML")); // "TrustedHTML"
```

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

| Specification |
| --- |
| Trusted Types # dom-trustedtypepolicyfactory-getpropertytype |

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

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


TrustedTypePolicyFactory: defaultPolicy property - Web APIs

TrustedTypePolicyFactory: defaultPolicy property
================================================

The **`defaultPolicy`** read-only property of the `TrustedTypePolicyFactory` interface returns the default `TrustedTypePolicy` or null if this is empty.

**Note:** Information about the creation and use of default policies can be found in the `createPolicy()` documentation.

Value
-----

A `TrustedTypePolicy` or null.

Examples
--------

The first line below returns null as no default policy has been created. Once a default policy is created, calling `defaultPolicy` returns that policy object.

```js
console.log(trustedTypes.defaultPolicy); // null
const dp = trustedTypes.createPolicy("default", {});
console.log(trustedTypes.defaultPolicy); // a TrustedTypePolicy object
```

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

| Specification |
| --- |
| Trusted Types # dom-trustedtypepolicyfactory-defaultpolicy |

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

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


TrustedTypePolicyFactory: isScript() method - Web APIs

TrustedTypePolicyFactory: isScript() method
===========================================

The **`isScript()`** method of the `TrustedTypePolicyFactory` interface returns true if it is passed a valid `TrustedScript` object.

**Note:** The purpose of the functions `isScript()`, `isHTML()`, and `isScriptURL()` is to check if the object is a valid TrustedType object, created by a configured policy.

Syntax
------

```js
isScript(value)
```

### Parameters

`value`

A `TrustedScript` object.

### Return value

A `boolean` that is true if the object is a valid `TrustedScript` object.

Examples
--------

In the below example the constant `url` was created by a policy, and therefore `isScriptURL()` returns true. The second example is an attempt to fake an object, and the third is a string. Both of these will return false when passed to `isScriptURL()`.

```js
const myScript = policy.createScript("eval('2 + 2')");
console.log(trustedTypes.isScript(myScript)); // true;

const fake = Object.create(TrustedScript.prototype);
console.log(trustedTypes.isScript(fake)); // false

console.log(trustedTypes.isScript("eval('2 + 2')")); // false
```

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

| Specification |
| --- |
| Trusted Types # dom-trustedtypepolicyfactory-isscript |

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

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


TrustedTypePolicyFactory: createPolicy() method - Web APIs

TrustedTypePolicyFactory: createPolicy() method
===============================================

The **`createPolicy()`** method of the `TrustedTypePolicyFactory` interface creates a `TrustedTypePolicy` object that implements the rules passed as `policyOptions`.

### The default policy

In Chrome a policy with a name of "default" creates a special policy that will be used if a string (rather than a Trusted Type object) is passed to an injection sink. This can be used in a transitional phase while moving from an application that inserted strings into injection sinks.

**Note:** The above behavior is not yet settled in the specification and may change in future.

**Warning:** A lax default policy could defeat the purpose of using Trusted Types, and therefore should be defined with strict rules to ensure it cannot be used to run dangerous code.

Syntax
------

```js
createPolicy(policyName, policyOptions)
```

### Parameters

`policyName`

A string with the name of the policy.

`policyOptions` Optional

User-defined functions for converting strings into trusted values.

`createHTML(input[,args])`

A callback function in the form of a string that contains code to run when creating a `TrustedHTML` object.

`createScript(input[,args])`

A callback function in the form of a string that contains code to run when creating a `TrustedScript` object.

`createScriptURL(input[,args])`

A callback function in the form of a string that contains code to run when creating a `TrustedScriptURL` object.

### Return value

A `TrustedTypePolicy` object.

### Exceptions

`TypeError`

Thrown if policy names are restricted by the Content Security Policy `trusted-types` directive and this name is not on the allowlist.

`TypeError`

Thrown if the name is a duplicate and the Content Security Policy trusted-types directive is not using `allow-duplicates`.

Examples
--------

The below code creates a policy with the name `"myEscapePolicy"` with a function defined for `createHTML()` which sanitizes HTML.

```js
const escapeHTMLPolicy = trustedTypes.createPolicy("myEscapePolicy", {
  createHTML: (string) => string.replace(/>/g, "<"),
});
```

### Creating a default policy

On a site where Trusted Types are enforced via a Content Security Policy with the `require-trusted-types-for` directive set to `script`, any injection script that accepts a script expects a Trusted Type object. In the case that a string is inserted instead, the following default policy will be used.

The policy logs a message to the console to remind the developer to refactor this part of the application to use a Trusted Type object. It also appends details of the use of the default policy, type, and injection sink to the returned value.

```js
trustedTypes.createPolicy("default", {
  createScriptURL: (s, type, sink) => {
    console.log("Please refactor.");
    return `${s}?default-policy-used&type=${encodeURIComponent(
 type,
 )}&sink=${encodeURIComponent(sink)}`;
  },
});
```

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

| Specification |
| --- |
| Trusted Types # dom-trustedtypepolicyfactory-createpolicy |

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

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


TrustedTypePolicyFactory: getAttributeType() method - Web APIs

TrustedTypePolicyFactory: getAttributeType() method
===================================================

The **`getAttributeType()`** method of the `TrustedTypePolicyFactory` interface allows web developers to check if a Trusted Type is required for an element, and if so which Trusted Type is used.

Syntax
------

```js
getAttributeType(tagName, attribute)
getAttributeType(tagName, attribute, elementNS)
getAttributeType(tagName, attribute, elementNS, attrNS)
```

### Parameters

`tagName`

A string containing the name of an HTML tag.

`attribute`

A string containing an attribute.

`elementNS` Optional

A string containing a namespace, if empty defaults to the HTML namespace.

`attrNS` Optional

A string containing a namespace, if empty defaults to null.

### Return value

A string with one of:

* `"TrustedHTML"`
* `"TrustedScript"`
* `"TrustedScriptURL"`

Or, null.

Examples
--------

In this example, passing the `<script>` element and `src` attribute to `getAttributeType` returns "TrustedScriptURL".

```js
console.log(trustedTypes.getAttributeType("script", "src")); // "TrustedScriptURL"
```

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

| Specification |
| --- |
| Trusted Types # dom-trustedtypepolicyfactory-getattributetype |

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

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


TrustedTypePolicyFactory: isScriptURL() method - Web APIs

TrustedTypePolicyFactory: isScriptURL() method
==============================================

The **`isScriptURL()`** method of the `TrustedTypePolicyFactory` interface returns true if it is passed a valid `TrustedScriptURL` object.

**Note:** The purpose of the functions `isScriptURL()`, `isHTML()`, and `isScript()` is to check if the object is a valid TrustedType object, created by a configured policy.

Syntax
------

```js
isScriptURL(value)
```

### Parameters

`value`

A `TrustedScriptURL` object.

### Return value

A `boolean`that is true if the object is a valid `TrustedScriptURL` object.

Examples
--------

In the below example the constant `url` was created by a policy, and therefore `isScriptURL()` returns true. The second example is an attempt to fake an object, and the third is a string. Both of these will return false when passed to `isScriptURL()`.

```js
const url = policy.createScriptURL("https://example.com/myscript.js");
console.log(trustedTypes.isScriptURL(url)); // true;

const fake = Object.create(TrustedScriptURL.prototype);
console.log(trustedTypes.isScriptURL(fake)); // false

console.log(trustedTypes.isScriptURL("https://example.com/myscript.js")); // false
```

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

| Specification |
| --- |
| Trusted Types # dom-trustedtypepolicyfactory-isscripturl |

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

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


Document: documentURI property - Web APIs

Document: documentURI property
==============================

 The **`documentURI`** read-only property of the
 `Document` interface returns the document location as a string.

Value
-----

A string.

Examples
--------

### JavaScript

```js
document.getElementById("url").textContent = document.documentURI;
```

### HTML

```html
<p id="urlText">
  URL:<br />
  <span id="url">URL goes here</span>
</p>
```

### Result

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-document-documenturi① |

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

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

See also
--------

* The `document.URL` property which returns the same value.


Document: enableStyleSheetsForSet() method - Web APIs

Document: enableStyleSheetsForSet() method
==========================================

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

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 Enables the style sheets matching the specified name in the current style sheet set,
 and disables all other style sheets (except those without a title, which are always
 enabled).

Syntax
------

```js
enableStyleSheetsForSet(name)
```

### Parameters

`name`

 The name of the style sheets to enable. All style sheets with a title that match
 this name will be enabled, while all others that have a title will be disabled.
 Specify an empty string for the *name* parameter to disable all alternate and
 preferred style sheets (but not the persistent style sheets; that is, those with no
 `title` attribute).

### Return value

None (`undefined`).

Notes
-----

* Title matches are case-sensitive.
* Calling this method with a `null` *name* has no effect; if you
 want to disable all alternate and preferred style sheets, you **must**
 pass "", the empty string.
* Stylesheets that don't have a title are never affected by this method.
* This method never affects the values of `document.lastStyleSheetSet` or
 `document.preferredStyleSheetSet`.
Examples
--------

```js
document.enableStyleSheetsForSet("Some style sheet set name");
```

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

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

See also
--------

* `Stylesheet`
* `Document.styleSheets`
* `document.lastStyleSheetSet`
* `document.preferredStyleSheetSet`
* `document.selectedStyleSheetSet`
* `document.enableStyleSheetsForSet()`


Document: head property - Web APIs

Document: head property
=======================

 The **`head`** read-only property of
 the `Document` interface returns the `<head>` element of
 the current document.

Value
-----

An `HTMLHeadElement`.

Examples
--------

```html
<!doctype html>
<head id="my-document-head">
  <title>Example: using document.head</title>
</head>

<script>
 const theHead = document.head;

 console.log(theHead.id); // "my-document-head";

 console.log(theHead === document.querySelector("head")); // true
</script>
```

Notes
-----

`document.head` is read-only. Trying to assign a value to this property will
 fail silently or, in Strict Mode, throws a `TypeError` .

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

| Specification |
| --- |
| HTML Standard # dom-document-head-dev |

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

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

See also
--------

* `document.body`


Document: pointerlockerror event - Web APIs

Document: pointerlockerror event
================================

The **`pointerlockerror`** event is fired when locking the pointer failed (for technical reasons or because the permission was denied).

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("pointerlockerror", (event) => {});

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

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

A generic `Event`.

Examples
--------

Using `addEventListener()`:

```js
const para = document.querySelector("p");

document.addEventListener("pointerlockerror", (event) => {
  console.log("Error locking pointer");
});
```

Using the `onpointerlockerror` event handler property:

```js
document.onpointerlockerror = (event) => {
  console.log("Error locking pointer");
};
```

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

| Specification |
| --- |
| Pointer Lock 2.0 # pointerlockchange-and-pointerlockerror-events |
| Pointer Lock 2.0 # dom-document-onpointerlockerror |

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

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

See also
--------

* Using Pointer Lock API


Document: startViewTransition() method - Web APIs

Document: startViewTransition() method
======================================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

 The **`startViewTransition()`** method of the
 View Transitions API starts a new view transition and returns a `ViewTransition` object to represent it.

When `startViewTransition()` is invoked, a sequence of steps is followed as explained in The view transition process.

Syntax
------

```js
startViewTransition(callback)
```

### Parameters

`callback`

A callback function typically invoked to update the DOM during the view transition process, which returns a `Promise`. The callback is invoked once the API has taken a screenshot of the current page. When the promise returned by the callback fulfills, the view transition begins in the next frame. If the promise returned by the callback rejects, the transition is abandoned.

### Return value

A `ViewTransition` object instance.

Examples
--------

### Basic usage

In our Basic View Transitions demo, the `updateView()` function handles both browsers that do and don't support the View Transitions API. In supporting browsers, we invoke `startViewTransition()` to set off the view transition process without worrying about the return value.

```js
function updateView(event) {
  // Handle the difference in whether the event is fired on the <a> or the <img>
  let targetIdentifier;
  if (event.target.firstChild === null) {
    targetIdentifier = event.target;
  } else {
    targetIdentifier = event.target.firstChild;
  }

  const displayNewImage = () => {
    const mainSrc = `${targetIdentifier.src.split("\_th.jpg")[0]}.jpg`;
    galleryImg.src = mainSrc;
    galleryCaption.textContent = targetIdentifier.alt;
  };

  // Fallback for browsers that don't support View Transitions:
  if (!document.startViewTransition) {
    displayNewImage();
    return;
  }

  // With View Transitions:
  const transition = document.startViewTransition(() => displayNewImage());
}
```

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

| Specification |
| --- |
| CSS View Transitions Module Level 1 # dom-document-startviewtransition |

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

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

See also
--------

* Smooth and simple transitions with the View Transitions API


Document: prepend() method - Web APIs

Document: prepend() method
==========================

 The **`Document.prepend()`** method
 inserts a set of `Node` objects or string objects before
 the first child of the document. String objects
 are inserted as equivalent `Text` nodes.

This method prepends a child to a `Document`. To prepend to an arbitrary element in the tree, see `Element.prepend()`.

Syntax
------

```js
prepend(param1)
prepend(param1, param2)
prepend(param1, param2, /\* …, \*/ paramN)
```

### Parameters

`param1`, …, `paramN`

A set of `Node` or string objects to insert.

### Return value

None (`undefined`).

### Exceptions

`HierarchyRequestError` `DOMException`

Thrown when the node cannot be inserted at the specified point in the hierarchy.

Examples
--------

### Prepending a root element to a document

 If you try to prepend an element to an existing HTML document,
 it might throw a `HierarchyRequestError' `DOMException` given a `<html>` element already exists.

```js
let html = document.createElement("html");
document.prepend(html);
// HierarchyRequestError: The operation would yield an incorrect node tree.
```

If you are creating a new document without any existing element, you can prepend a root HTML element (or a root SVG element):

```js
let doc = new Document();
let html = document.createElement("html");
doc.prepend(html);

doc.children; // HTMLCollection [<html>]
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-parentnode-prepend① |

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

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

See also
--------

* `Document.append()`
* `Element.prepend()`


Document: beforescriptexecute event - Web APIs

Document: beforescriptexecute event
===================================

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The `beforescriptexecute` event fires when a static `<script>` is about to start executing. It does not fire if the element is added dynamically, such as with `appendChild()`.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

```js
function starting(e) {
  logMessage(`Starting script with ID: ${e.target.id}`);
}

document.addEventListener("beforescriptexecute", starting, true);
// or
document.onbeforescriptexecute = starting;
```

View Live Example

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

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

See also
--------

* `Document.afterscriptexecute_event`
* `Document.currentScript`


Document: featurePolicy property - Web APIs

Document: featurePolicy property
================================

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

The **`featurePolicy`** read-only property of the `Document` interface returns the `FeaturePolicy` interface which provides a simple API for inspecting the Permissions Policies applied to a specific document.

Value
-----

A `FeaturePolicy` object that can be used to inspect the Permissions Policy settings applied to the document.

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

#### No specification found

No specification data found for `api.Document.featurePolicy`.
Check for problems with this page or contribute a missing `spec_url` to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

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

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


Document: getElementsByTagNameNS() method - Web APIs

Document: getElementsByTagNameNS() method
=========================================

 Returns a list of elements with the given tag name belonging to the given namespace.
 The complete document is searched, including the root node.

Syntax
------

```js
getElementsByTagNameNS(namespace, name)
```

### Parameters

`namespace`

 The namespace URI of elements to look for (see
 `element.namespaceURI`).

`name`

 Either the local name of elements to look for or the special
 value `*`, which matches all elements (see `element.localName`).

### Return value

 A live `NodeList` (but see the note below) of
 found elements in the order they appear in the tree.

**Note:** While the W3C specification says returned value is a `NodeList`, this method returns a `HTMLCollection` in Firefox.
 Opera returns a `NodeList`, but with a `namedItem` method implemented, which makes it similar to a `HTMLCollection`. As of January 2012, only in WebKit browsers is the returned value a pure `NodeList`.
 See bug 14869 for details.

**Note:** Currently parameters in this method are case-sensitive, but they were case-insensitive in Firefox 3.5 and before.
 See the developer release note for Firefox 3.6 and a note in Browser compatibility section in `Element.getElementsByTagNameNS` for details.

Examples
--------

 In the following example `getElementsByTagNameNS` starts from a particular
 parent element, and searches topdown recursively through the DOM from that parent
 element, looking for child elements matching the tag `name` parameter.

 Note that when the node on which `getElementsByTagName` is invoked is not
 the `document` node, in fact the
 `element.getElementsByTagNameNS` method is used.

 To use the following example, just copy/paste it into a new file saved with the .xhtml
 extension.

```html
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>getElementsByTagNameNS example</title>

    <script>
 function getAllParaElems() {
 const allParas = document.getElementsByTagNameNS(
 "http://www.w3.org/1999/xhtml",
 "p",
 );
 const num = allParas.length;
 alert(`There are ${num} <p> elements in this document`);
 }

 function div1ParaElems() {
 const div1 = document.getElementById("div1");
 const div1Paras = div1.getElementsByTagNameNS(
 "http://www.w3.org/1999/xhtml",
 "p",
 );
 const num = div1Paras.length;
 alert(`There are ${num} <p> elements in div1 element`);
 }

 function div2ParaElems() {
 const div2 = document.getElementById("div2");
 const div2Paras = div2.getElementsByTagNameNS(
 "http://www.w3.org/1999/xhtml",
 "p",
 );
 const num = div2Paras.length;
 alert(`There are ${num} <p> elements in div2 element`);
 }
 </script>
  </head>

  <body style="border: solid green 3px">
    <p>Some outer text</p>
    <p>Some outer text</p>

    <div id="div1" style="border: solid blue 3px">
      <p>Some div1 text</p>
      <p>Some div1 text</p>
      <p>Some div1 text</p>

      <div id="div2" style="border: solid red 3px">
        <p>Some div2 text</p>
        <p>Some div2 text</p>
      </div>
    </div>

    <p>Some outer text</p>
    <p>Some outer text</p>

    <button onclick="getAllParaElems();">
      Show all p elements in document
    </button>
    <br />

    <button onclick="div1ParaElems();">
      Show all p elements in div1 element
    </button>
    <br />

    <button onclick="div2ParaElems();">
      show all p elements in div2 element
    </button>
  </body>
</html>
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-document-getelementsbytagnamens① |

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

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

See also
--------

* `Element.getElementsByTagNameNS()`