recursal/MDN huggingface dataset:
DOMTokenList: contains() method
===============================

 The **`contains()`** method of the `DOMTokenList` interface
 returns a boolean value — `true` if the underlying list contains the given token,
 otherwise `false`.

Syntax
------


```js
contains(token)
```

### Parameters

`token`

 A string representing the token
 you want to check for the existence of in the list.


### Return value

 A boolean value, which is `true` if the calling list contains
 `token`, otherwise `false`.

Examples
--------

 In the following example we retrieve the list of classes set on a
 `<span>` element as a `DOMTokenList` using
 `Element.classList`. We then test for the existence of `"c"` in
 the list, and write the result into the `<span>`'s
 `Node.textContent`.

First, the HTML:


```html
<span class="a b c"></span>
```


Now the JavaScript:


```js
const span = document.querySelector("span");
span.textContent = span.classList.contains("c")
  ? "The classList contains 'c'"
  : "The classList does not contain 'c'";
```


The output looks like this:

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-domtokenlist-contains① |

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

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
DOMTokenList: length property
=============================

 The read-only **`length`** property of the `DOMTokenList` interface is an `integer` representing the number
 of objects stored in the object.

Value
-----

An positive integer, or `0` if the list is empty.

Examples
--------

 In the following example we retrieve the list of classes set on a
 `<span>` element as a `DOMTokenList` using
 `Element.classList`, then write the length of the list to the
 `<span>`'s `Node.textContent`.

First, the HTML:


```html
<span class="a b c"></span>
```


Now the JavaScript:


```js
const span = document.querySelector("span");
const classes = span.classList;
const length = classes.length;

span.textContent = `classList length = ${length}`;
```


The output looks like this:

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-domtokenlist-length① |

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

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
DOMTokenList: keys() method
===========================

 The **`keys()`** method of the `DOMTokenList` interface
 returns an iterator allowing to go through all keys contained in this object.
 The keys are unsigned integers.

Syntax
------


```js
keys()
```

### Parameters

None.

### Return value

Returns an iterator.

Examples
--------

 In the following example we retrieve the list of classes set on a
 `<span>` element as a `DOMTokenList` using
 `Element.classList`. We then retrieve an iterator containing the keys using `keys()`,
 then iterate through those keys using a for...of loop,
 writing each one to the `<span>`'s `Node.textContent`.

First, the HTML:


```html
<span class="a b c"></span>
```


Now the JavaScript:


```js
const span = document.querySelector("span");
const classes = span.classList;
const iterator = classes.keys();

for (let value of iterator) {
  span.textContent += `(${value}) `;
}
```


The output looks like this:

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

#### No specification found

No specification data found for `api.DOMTokenList.keys`.  
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.

See also
--------

* `DOMTokenList.entries()`, `DOMTokenList.forEach()` and `DOMTokenList.values`.
DOMTokenList: values() method
=============================

 The **`values()`** method of the `DOMTokenList` interface
 returns an `iterator`
 allowing the caller to go through all values contained in the `DOMTokenList`.
 The individual values are strings.

Syntax
------


```js
tokenList.values()
```

### Parameters

None.

### Return value

Returns an `iterator`.

Examples
--------

 In the following example we retrieve the list of classes set on a
 `<span>` element as a `DOMTokenList` using
 `Element.classList`. We when retrieve an iterator containing the values
 using `values()`, then iterate through those values using a for...of loop,
 writing each one to the `<span>`'s `Node.textContent`.

First, the HTML:


```html
<span class="a b c"></span>
```


Now the JavaScript:


```js
const span = document.querySelector("span");
const classes = span.classList;
const iterator = classes.values();

for (const value of iterator) {
  span.textContent += `(${value}) `;
}
```


The output looks like this:

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

#### No specification found

No specification data found for `api.DOMTokenList.values`.  
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.
DOMTokenList: forEach() method
==============================

 The **`forEach()`** method of the `DOMTokenList` interface
 calls the callback given in parameter once for each value pair in the list, in
 insertion order.

Syntax
------


```js
forEach(callback)
forEach(callback, thisArg)
```

### Parameters

`callback`

The function to execute for each element, eventually taking three arguments:

`currentValue`

The current element being processed in the array.

`currentIndex`

The index of the current element being processed in the array.

`listObj`

The array that `forEach()` is being applied to.


`thisArg` Optional

The value to use as `this` when executing `callback`.

### Return value

None.

Example
-------

 In the following example we retrieve the list of classes set on a
 `<pre>` element as a `DOMTokenList` using
 `Element.classList`. We when retrieve an iterator containing the values
 using `forEach()`, writing each one to the `<pre>`'s
 `Node.textContent` inside the `forEach()` inner function.

### HTML


```html
<pre class="a b c"></pre>
```

### JavaScript


```js
const pre = document.querySelector("pre");
const classes = pre.classList;
const iterator = classes.values();

classes.forEach(function (value, key, listObj) {
  pre.textContent += `(${value} ${key})/${this}\n`;
}, "arg");
```

### Result

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

#### No specification found

No specification data found for `api.DOMTokenList.forEach`.  
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.

See also
--------

* `DOMTokenList.entries()`, `DOMTokenList.keys` and `DOMTokenList.values`.
DOMTokenList: toggle() method
=============================

 The **`toggle()`** method of the `DOMTokenList` interface
 removes an existing token from the list and returns `false`.
 If the token doesn't exist it's added and the function returns `true`.

Syntax
------


```js
toggle(token)
toggle(token, force)
```

### Parameters

`token`

A string representing the token you want to toggle.

`force` Optional

 If included, turns the toggle into a one way-only operation.
 If set to `false`, then `token` will *only* be removed, but not added.
 If set to `true`, then `token` will *only* be added, but not removed.


### Return value

 A boolean value, `true` or `false`, indicating whether `token` is in the
 list after the call or not.

Examples
--------

### Toggling a class on click

 In the following example we retrieve the list of classes set on a
 `<span>` element as a `DOMTokenList` using
 `Element.classList`. We then replace a token in the list, and write the
 list into the `<span>`'s `Node.textContent`.

First, the HTML:


```html
<span class="a b">classList is 'a b'</span>
```


Now the JavaScript:


```js
const span = document.querySelector("span");
const classes = span.classList;

span.addEventListener("click", () => {
  const result = classes.toggle("c");
  span.textContent = `'c' ${
 result ? "added" : "removed"
 }; classList is now "${classes}".`;
});
```


The output looks like this and it will change each time you click on the text:

### Setting the force parameter

The second parameter can be used to determine whether the class is included or not. This example would include the 'c' class only if the browser window is over 1000 pixels wide:


```js
span.classList.toggle("c", window.innerWidth > 1000);
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-domtokenlist-toggle① |

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

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
Client: postMessage() method
============================

 The **`postMessage()`** method of the
 `Client` interface allows a service worker to send a message to a client
 (a `Window`, `Worker`, or `SharedWorker`). The
 message is received in the "`message`" event on
 `navigator.serviceWorker`.

Syntax
------


```js
postMessage(message)
postMessage(message, options)
postMessage(message, transferables)
```

### Parameters

`message`

The message to send to the client. This can be any structured-cloneable type.

`options` Optional

An optional object containing a `transfer` field with an array of transferable objects to transfer ownership of. The ownership of these objects is given to the destination side and they are no longer usable on the sending side.

`transferables` Optional

An optional array of transferable objects to transfer ownership of. The ownership of these objects is given to the destination side and they are no longer usable on the sending side.

### Return value

None (`undefined`).

Examples
--------

The code below sends a message from a service worker to a client. The client is fetched using the `get()` method on `clients`, which is a global in service worker scope.


```js
addEventListener("fetch", (event) => {
  event.waitUntil(
    (async () => {
      // Exit early if we don't have access to the client.
      // Eg, if it's cross-origin.
      if (!event.clientId) return;

      // Get the client.
      const client = await self.clients.get(event.clientId);
      // Exit early if we don't get the client.
      // Eg, if it closed.
      if (!client) return;

      // Send a message to the client.
      client.postMessage({
        msg: "Hey I just got a fetch from you!",
        url: event.request.url,
      });
    })(),
  );
});
```


Receiving that message:


```js
navigator.serviceWorker.addEventListener("message", (event) => {
  console.log(event.data.msg, event.data.url);
});
```

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

| Specification |
| --- |
| Service Workers # dom-client-postmessage-message-options |

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

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
Client: url property
====================

 The **`url`** read-only property of the `Client`
 interface returns the URL of the current service worker client.

Value
-----

A string.

Examples
--------


```js
self.addEventListener("notificationclick", (event) => {
  console.log("On notification click: ", event.notification.tag);
  event.notification.close();

  // This looks to see if the current is already open and
  // focuses if it is
  event.waitUntil(
    clients
      .matchAll({
        type: "window",
      })
      .then((clientList) => {
        for (const client of clientList) {
          if (client.url === "/" && "focus" in client) {
            return client.focus();
          }
        }
        if (clients.openWindow) {
          return clients.openWindow("/");
        }
      }),
  );
});
```

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

| Specification |
| --- |
| Service Workers # client-url |

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

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
Client: frameType property
==========================

The **`frameType`** read-only property of the `Client` interface indicates the type of browsing context of the current `Client`. This value can be one of `"auxiliary"`, `"top-level"`, `"nested"`, or `"none"`.

Value
-----

One of these four strings: `"auxiliary"`, `"top-level"`, `"nested"`, or `"none"`.

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

| Specification |
| --- |
| Service Workers # client-frametype |

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

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
Client: id property
===================

The **`id`** read-only property of the `Client` interface returns the universally unique identifier of the `Client` object.

Value
-----

A string uniquely identifying the object.

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

| Specification |
| --- |
| Service Workers # client-id |

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

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
Client: type property
=====================

 The **`type`** read-only property of the `Client`
 interface indicates the type of client the service worker is controlling.

Value
-----

A string, representing the client type. The value can be one of

* `"window"`
* `"worker"`
* `"sharedworker"`
Examples
--------


```js
// service worker client (e.g. a document)
function sendMessage(message) {
  return new Promise((resolve, reject) => {
    // note that this is the ServiceWorker.postMessage version
    navigator.serviceWorker.controller.postMessage(message);
    window.serviceWorker.onMessage = (e) => {
      resolve(e.data);
    };
  });
}

// controlling service worker
self.addEventListener("message", (e) => {
  // e.source is a client object
  e.source.postMessage(`Hello! Your message was: ${e.data}`);
  // Let's also post the type value back to the client
  e.source.postMessage(e.source.type);
});
```

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

| Specification |
| --- |
| Service Workers # client-type |

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

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
WebTransportReceiveStream: getStats() method
============================================

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

The **`getStats()`** method of the `WebTransportReceiveStream` interface asynchronously returns an object containing statistics for the current stream.

 The statistics include the total number of ordered bytes that have arrived on this stream (ignoring network overhead, up until the first missing byte) and the total number that have been read by the application.
 It therefore provides a measure of how quickly the application is consuming bytes from the server on this particular stream.

**Note:** This feature is available in Web Workers

Syntax
------


```js
getStats()
```

### Parameters

None.

### Return value

 A `Promise` that resolves to a object containing statistics about the current stream.
 The returned object has the following properties:

`timestamp`

A `DOMHighResTimeStamp` indicating the timestamp at which the statistics were gathered, relative to Jan 1, 1970, UTC.

`bytesReceived`

 A positive integer indicating the number of bytes received by this stream, up to the first missing byte.
 The number does not include any network overhead, and can only increase.


`bytesRead`

 A positive integer indicating the number of bytes the application has read from this `WebTransportReceiveStream` stream.
 This number can only increase, and is always less than or equal to `bytesReceived`.


Examples
--------

 The code snippet below uses `await` to wait on the `Promise` returned by `getStats()`.
 When the promise fulfills, the number of bytes that have not yet been read is logged to the console.


```js
const stats = await stream.getStats();
const unConsumedBytes = stats.bytesReceived - stats.bytesRead;
console.log(`Bytes in reader queue: ${unConsumedBytes}`);
```

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

| Specification |
| --- |
| WebTransport # dom-webtransportreceivestream-getstats |

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

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
MediaDeviceInfo: toJSON() method
================================

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

The **`toJSON()`** method of the `MediaDeviceInfo` interface is a serializer; it returns a JSON representation of the `MediaDeviceInfo` object.

Syntax
------


```js
toJSON()
```

### Parameters

None.

### Return value

A `JSON` object that is the serialization of the `MediaDeviceInfo` object.

### Examples


```js
if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) {
  console.log("enumerateDevices() not supported.");
} else {
  // List cameras and microphones.
  navigator.mediaDevices
    .enumerateDevices()
    .then((devices) => {
      devices.forEach((device) => {
        console.log(device.toJSON());
      });
    })
    .catch((err) => {
      console.log(`${err.name}: ${err.message}`);
    });
}
```


This might produce:


```bash
Object { deviceId: "HJtTemQTM64Bivxv3ZEyKjCi1VR8042lPNpmXKObKJE=", kind: "videoinput", label: "", groupId: "Okm2l1YZTrwy8awTxE8QSLNFoVMdIXx++wLh68tbmv0=" }
Object { deviceId: "EqDubLxPlPeW+5w/ereWTF/3EaAMVHh9QBBHkZHiP0k=", kind: "audioinput", label: "", groupId: "Okm2l1YZTrwy8awTxE8QSLNFoVMdIXx++wLh68tbmv0=" }
Object { deviceId: "CanWttL2RnHOiS7FzzYXMIvLqVFE5S06Lfy8H//nhEw=", kind: "audioinput", label: "", groupId: "nOdLNeXGIw9oL9f2wH69SssQpRVs7cmt9jqZrUWgQwI=" }
```

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

| Specification |
| --- |
| Media Capture and Streams # dom-mediadeviceinfo-tojson |

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

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

See also
--------

* `JSON`
MediaDeviceInfo: kind property
==============================

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

 The **`kind`** read-only property of
 the `MediaDeviceInfo` interface returns an enumerated value, that is
 either `"videoinput"`, `"audioinput"` or `"audiooutput"`.

Value
-----

One of `"videoinput"`, `"audioinput"` or `"audiooutput"`.

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

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

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

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
MediaDeviceInfo: groupId property
=================================

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

 The **`groupId`** read-only property of
 the `MediaDeviceInfo` interface returns a string that
 is a group identifier.

 Two devices have the same group identifier if they
 belong to the same physical device; for example, a monitor with both a built-in camera
 and microphone.

Value
-----

 A string which uniquely identifies the group of related devices to
 which this device belongs.

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

| Specification |
| --- |
| Media Capture and Streams # dom-mediadeviceinfo-groupid |

Examples
--------

 In this example, we assemble a list of the devices which are part of the same group as
 a given device. This might be used to produce a user interface that gathers associated
 devices together for presentation purposes, or to make it easy for the user to choose to
 use the built-in camera and microphone on the same display at the same time.


```js
const getDeviceGroup = (mainDevInfo) => {
  let devList = [];

  navigator.mediaDevices.enumerateDevices().then((devices) => {
    devices.forEach((device) => {
      if (device.groupId === mainDevInfo.groupId) {
        devList.push(device);
      }
    });
  });

  return devList;
};
```


 The `getDeviceGroup()` function takes as input the
 `MediaDeviceInfo` object describing the device for which a group list is to
 be built. The function starts by initializing the result array, `devList`, to
 be an empty array.

 Then `navigator.mediaDevices.enumerateDevices()` is called to get the list of all media
 devices. Once the promise resolves, we walk the list using `forEach()`. For each device, if its `groupId` matches the main device's `groupId`, we push the
 `MediaDeviceInfo` object onto the list.

 Finally, the list, which now contains a `MediaDeviceInfo` object for each
 device in the same group, is returned to the caller.

 This could be altered easily to either leave out the passed-in device from the returned
 list, or to place it at the top of the list, by comparing the two objects'
 `deviceId` values, only pushing the device onto
 the result list if it doesn't match.

 This version of the example puts the passed-in device at the top of the result list,
 then adds any other members of the group that are found:


```js
const getDeviceGroup = (mainDevInfo) => {
  let devList = [mainDevInfo];

  navigator.mediaDevices.enumerateDevices().then((devices) => {
    devices.forEach((device) => {
      if (
        device.groupId === mainDevInfo.groupId &&
        device.deviceId !== mainDevInfo.deviceId
      ) {
        devList.push(device);
      }
    });
  });

  return devList;
};
```

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

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
MediaDeviceInfo: deviceId property
==================================

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

 The **`deviceId`** read-only property
 of the `MediaDeviceInfo` interface returns a string
 that is an identifier for the represented device and is persisted across
 sessions.

 It is un-guessable by other applications, and unique to the origin of
 the calling application. It is reset when the user clears cookies. For private browsing,
 a different identifier is used that is not persisted across sessions.

Value
-----

A string.

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

| Specification |
| --- |
| Media Capture and Streams # dom-mediadeviceinfo-deviceid |

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

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
MediaDeviceInfo: label property
===============================

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

 The **`label`** read-only
 property of the `MediaDeviceInfo` interface returns a
 string describing this device (for example
 "External USB Webcam").

 Only available during active `MediaStream`
 use, or when persistent permissions have been granted.

Value
-----

 A string which describes the media device. For security reasons, the
 `label` is always an empty string (`""`) if the user has not
 obtained permission to use at least one media device, either by starting a stream from
 the microphone or camera, or by persistent permissions being granted.

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

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

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

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