Storage: key() method - Web APIs

Storage: key() method
=====================

 The **`key()`** method of the `Storage` interface,
 when passed a number n, returns the name of the nth key in a given `Storage`
 object. The order of keys is user-agent defined, so you should not rely on it.

Syntax
------

```js
key(index)
```

### Parameters

`index`

 An integer representing the number of the key you want to get the name of. This is a
 zero-based index.

### Return value

 A string containing the name of the key. If the index does not exist,
 `null` is returned.

Examples
--------

The following function iterates over the local storage keys:

```js
function forEachKey(callback) {
  for (let i = 0; i < localStorage.length; i++) {
    callback(localStorage.key(i));
  }
}
```

 The following function iterates over the local storage keys and gets the value set for
 each key:

```js
for (let i = 0; i < localStorage.length; i++) {
  console.log(localStorage.getItem(localStorage.key(i)));
}
```

**Note:** For a real-world example, see our Web Storage Demo.

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

| Specification |
| --- |
| HTML Standard # dom-storage-key-dev |

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

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

See also
--------

* Using the Web Storage API


Storage: getItem() method - Web APIs

Storage: getItem() method
=========================

 The **`getItem()`** method of the `Storage`
 interface, when passed a key name, will return that key's value, or `null` if
 the key does not exist, in the given `Storage` object.

Syntax
------

```js
getItem(keyName)
```

### Parameters

`keyName`

 A string containing the name of the key you want to retrieve the
 value of.

### Return value

 A string containing the value of the key. If the key does not exist,
 `null` is returned.

Examples
--------

 The following function retrieves three data items from local storage, then uses them to
 set custom styles on a page.

```js
function setStyles() {
  const currentColor = localStorage.getItem("bgcolor");
  const currentFont = localStorage.getItem("font");
  const currentImage = localStorage.getItem("image");

  document.getElementById("bgcolor").value = currentColor;
  document.getElementById("font").value = currentFont;
  document.getElementById("image").value = currentImage;

  htmlElem.style.backgroundColor = `#${currentColor}`;
  pElem.style.fontFamily = currentFont;
  imgElem.setAttribute("src", currentImage);
}
```

**Note:** To see this used within a real-world example, see our Web Storage Demo.

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

| Specification |
| --- |
| HTML Standard # dom-storage-getitem-dev |

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

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

See also
--------

* Storage.setItem()
* Using the Web Storage API


Storage: length property - Web APIs

Storage: length property
========================

 The **`length`** read-only property of the
 `Storage` interface returns the number of data items stored in a given
 `Storage` object.

Value
-----

The number of items stored in the `Storage` object.

Examples
--------

 The following function adds three data items to the local storage for the current
 domain, then returns the number of items in the storage:

```js
function populateStorage() {
  localStorage.setItem("bgcolor", "yellow");
  localStorage.setItem("font", "Helvetica");
  localStorage.setItem("image", "cats.png");

  return localStorage.length; // Should return 3
}
```

**Note:** For a real-world example, see our Web Storage Demo.

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

| Specification |
| --- |
| HTML Standard # dom-storage-length-dev |

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

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

See also
--------

* Using the Web Storage API


Storage: clear() method - Web APIs

Storage: clear() method
=======================

 The **`clear()`** method of the `Storage`
 interface clears all keys stored in a given `Storage` object.

Syntax
------

```js
clear()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

 The following function creates three data entries in local storage, and then deletes
 them by using `clear()`.

```js
function populateStorage() {
  localStorage.setItem("bgcolor", "red");
  localStorage.setItem("font", "Helvetica");
  localStorage.setItem("image", "miGato.png");

  localStorage.clear();
}
```

**Note:** For a real-world example, see our Web Storage Demo.

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

| Specification |
| --- |
| HTML Standard # dom-storage-clear-dev |

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

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

See also
--------

Using the Web Storage API


TextTrack: cuechange event - Web APIs

TextTrack: cuechange event
==========================

The **`cuechange`** event fires when a `TextTrack` has changed the currently displaying cues. The event is fired on both the `TextTrack` and the `HTMLTrackElement` in which it's being presented, if any.

Syntax
------

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

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

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

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

A generic `Event` with no added properties.

Examples
--------

You can set up a listener for the `cuechange` event on a `TextTrack` using the `addEventListener()` method:

```js
track.addEventListener("cuechange", () => {
  const cues = track.activeCues; // array of current cues
  // …
});
```

Or you can set the `oncuechange` event handler property:

```js
track.oncuechange = (event) => {
  let cues = track.activeCues; // array of current cues
};
```

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

| Specification |
| --- |
| HTML Standard # event-media-cuechange |
| HTML Standard # handler-texttrack-oncuechange |

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

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

See also
--------

* WebVTT
* The same event on `HTMLTrackElement`: `cuechange`


TextTrack: mode property - Web APIs

TextTrack: mode property
========================

 The `TextTrack` interface's
 **`mode`** property is a string specifying and controlling the
 text track's mode: `disabled`, `hidden`, or
 `showing`. You can read this value to determine the current mode,
 and you can change this value to switch modes.

 Safari additionally requires the **`default`**
 boolean attribute to be set to true when implementing your own video player controls in
 order for the subtitles cues to be shown.

### Value

A string which indicates the track's current mode. One of:

`disabled`

 The text track is currently disabled. While the track's presence is exposed in the
 DOM, the user agent is otherwise ignoring it. No cues are active, no events are being
 fired, and the user agent won't attempt to obtain the track's cues. This is the
 default value, unless the text track has the `default`
 Boolean attribute is specified, in which case the default is `showing`.

`hidden`

 The text track is currently active but the cues aren't being displayed. If the user
 agent hasn't tried to obtain the track's cues yet, it will do so soon (thereby
 populating the track's `TextTrack.cues` property). The user agent is
 keeping a list of the active cues (in the track's `activeCues` property) and events are being fired at the corresponding times, even
 though the text isn't being displayed.

`showing`

 The text track is currently enabled and is visible. If the track's cues list hasn't
 been obtained yet, it will be soon. The `activeCues` list is being maintained and events are firing at the appropriate
 times; the track's text is also being drawn appropriately based on the styling and the
 track's `kind`. This is the default value if the text
 track's `default` Boolean attribute is specified.

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

 The default `mode` is `disabled`, unless the
 `default` Boolean attribute is specified, in which case the
 default `mode` is `showing`. When a text track is loaded in the
 `disabled` state, the corresponding WebVTT file is not loaded until the state
 changes to either `showing` or `hidden`. This way, the resource
 fetch and memory usage are avoided unless the cues are actually needed.

 However, that means that if you wish to perform any actions involving the track's cues
 while handling, for example, the `load` event—in order to process some aspect
 of the cues upon page load—and the track mode was initially `disabled`,
 you'll have to change the `mode` to either `hidden` or
 `showing` in order to trigger loading of the cues.

 When the mode is `showing`, text tracks are performed. The exact appearance
 and manner of that performance varies depending on each text track's
 `kind`. In general:

* Tracks whose `kind` is `"subtitles"` or
 `"captions"` are rendered with the cues overlaid over the top of the video.
* Tracks whose `kind` is `"descriptions"` are presented in a
 non-visual form (for example, the text might be spoken to describe the action in the
 video).
* Tracks whose `kind` is `"chapters"` are used by the user agent
 or the website or web app to construct and present an interface for navigating the
 named chapters, where each cue in the list represents a chapter in the media. The user
 can then navigate to the desired chapter, which begins at the cue's start position and
 ends at the cue's end position.
Example
-------

 In this example, we configure the text track's cues so that every time a cue is
 finished, the video automatically pauses playback. This is done by setting the
 `pauseOnExit` property on each cue to
 `true`. However, to ensure that the track's cues are available, we first set
 `mode` to `showing`.

```js
window.addEventListener("load", (event) => {
  let trackElem = document.querySelector("track");
  let track = trackElem.track;

  track.mode = "showing";

  for (const cue of track.cues) {
    cue.pauseOnExit = true;
  }
});
```

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

| Specification |
| --- |
| HTML Standard # dom-texttrack-mode-dev |

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

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

See also
--------

* WebVTT
* `TextTrack`
* `TextTrackList`
* `TextTrackCueList`
* `VTTCue`
* `<track>`
* `HTMLTrackElement`


TextTrack: kind property - Web APIs

TextTrack: kind property
========================

The **`kind`** read-only property of the `TextTrack` interface returns the kind of text track this object represents. This decides how the track will be handled by a user agent.

Value
-----

A string. One of:

`"subtitles"`

The cues are overlaid on the video. Positioning of the cues is controlled using the properties of an object that inherits from `TextTrackCue`, for example `VTTCue`.

`"captions"`

The cues are overlaid on the video. Positioning of the cues is controlled using the properties of an object that inherits from `TextTrackCue`, for example `VTTCue`.

`"descriptions"`

The cues are made available in a non-visual fashion.

`"chapters"`

The user agent will make available a mechanism to navigate by selecting a cue.

`"metadata"`

Additional data related to the media data, which could be used for interactive views.

Examples
--------

In the following example the value of `kind` is printed to the console.

```js
let video = document.querySelector("video");
let track = video.addTextTrack("captions", "Captions", "en");
track.mode = "showing";
console.log(track.kind);
```

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

| Specification |
| --- |
| HTML Standard # dom-texttrack-kind-dev |

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

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


TextTrack: activeCues property - Web APIs

TextTrack: activeCues property
==============================

The **`activeCues`** read-only property of the `TextTrack` interface returns a `TextTrackCueList` object listing the currently active cues.

Value
-----

A `TextTrackCueList` object.

Examples
--------

The following example adds a new `TextTrack` to a video. The `activeCues` are printed to the console.

```js
let video = document.querySelector("video");
let track = video.addTextTrack("captions", "Captions", "en");
track.mode = "showing";
console.log(track.activeCues);
```

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

| Specification |
| --- |
| HTML Standard # dom-texttrack-activecues-dev |

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

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


TextTrack: removeCue() method - Web APIs

TextTrack: removeCue() method
=============================

The **`removeCue()`** method of the `TextTrack` interface removes a cue from the list of cues.

Syntax
------

```js
removeCue(cue)
```

### Parameters

`cue`

A `TextTrackCue`.

### Return value

Undefined.

### Exceptions

`NotFoundError` `DOMException`

Thrown if the given cue is not found in the list of cues.

**Note:** The `TextTrackCue` interface is an abstract class used as the parent for other cue interfaces such as `VTTCue`. Therefore, when removing a cue you will be passing in one of the cue types that inherit from `TextTrackCue`.

Examples
--------

In the following example a cue is added to a video text track using `addCue()`, then removed using `removeCue`.

```js
let video = document.querySelector("video");
let track = video.addTextTrack("captions", "Captions", "en");
track.mode = "showing";
let cue = new VTTCue(0, 0.9, "Hildy!");
track.addCue(cue);
track.removeCue(cue);
```

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

| Specification |
| --- |
| HTML Standard # dom-texttrack-removecue-dev |

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

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


TextTrack: cues property - Web APIs

TextTrack: cues property
========================

The **`cues`** read-only property of the `TextTrack` interface returns a `TextTrackCueList` object containing all of the track's cues.

Value
-----

A `TextTrackCueList` object.

Examples
--------

In the following example two cues are added to a video text track using `addCue()`. The value of `cues` is printed to the console. The returned `TextTrackCueList` object contains the two cues.

```js
let video = document.querySelector("video");
let track = video.addTextTrack("captions", "Captions", "en");
track.mode = "showing";
track.addCue(new VTTCue(0, 0.9, "Hildy!"));
track.addCue(new VTTCue(1, 1.4, "How are you?"));
console.log(track.cues);
```

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

| Specification |
| --- |
| HTML Standard # dom-texttrack-cues-dev |

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

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


TextTrack: inBandMetadataTrackDispatchType property - Web APIs

TextTrack: inBandMetadataTrackDispatchType property
===================================================

The **`inBandMetadataTrackDispatchType`** read-only property of the `TextTrack` interface returns the text track's in-band metadata dispatch type of the text track represented by the `TextTrack` object.

An in-band metadata dispatch type is a string extracted from a media resource specifically for in-band metadata tracks. An example of a media resource that might have such tracks is a TV station streaming a broadcast on the web. Text Tracks may be used to include metadata for ad targeting, additional information such as recipe data during a cooking show, or trivia game data during a game show.

The value of this attribute could be used to attach these tracks to dedicated script modules as they are loaded.

Value
-----

A string containing the `inBandMetadataTrackDispatchType`, or an empty string.

Examples
--------

In the following example the value of `inBandMetadataTrackDispatchType` is printed to the console.

```js
let video = document.querySelector("video");
let track = video.addTextTrack("captions", "Captions", "en");
track.mode = "showing";
console.log(track.inBandMetadataTrackDispatchType);
```

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

| Specification |
| --- |
| HTML Standard # dom-texttrack-label-dev |

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

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


TextTrack: addCue() method - Web APIs

TextTrack: addCue() method
==========================

The **`addCue()`** method of the `TextTrack` interface adds a new cue to the list of cues.

Syntax
------

```js
addCue(cue)
```

### Parameters

`cue`

A `TextTrackCue`.

**Note:** The `TextTrackCue` interface is an abstract class used as the parent for other cue interfaces such as `VTTCue`. Therefore, when adding a cue you will be using one of the cue types that inherit from `TextTrackCue`.

### Return value

Undefined.

### Exceptions

`InvalidStateError` `DOMException`

Thrown if the rules for this `TextTrackList` do not match those that are appropriate for the incoming `TextTrackCue`.

Examples
--------

In the following example two cues are added to a video text track using `addCue()`.

```js
let video = document.querySelector("video");
let track = video.addTextTrack("captions", "Captions", "en");
track.mode = "showing";
track.addCue(new VTTCue(0, 0.9, "Hildy!"));
track.addCue(new VTTCue(1, 1.4, "How are you?"));
```

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

| Specification |
| --- |
| HTML Standard # dom-texttrack-addcue-dev |

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

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


TextTrack: language property - Web APIs

TextTrack: language property
============================

The **`language`** read-only property of the `TextTrack` interface returns the language of the text track.

This uses the same values as the HTML `lang` attribute. These values are documented in RFC 5646: Tags for Identifying Languages (also known as BCP 47).

Value
-----

A string containing a language identifier. For example, `"en-US"` for United States English or `"pt-BR"` for Brazilian Portuguese.

Examples
--------

In the following example the value of `language` is printed to the console.

```js
let video = document.querySelector("video");
let track = video.addTextTrack("captions", "Captions", "en-US");
track.mode = "showing";
console.log(track.language);
```

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

| Specification |
| --- |
| HTML Standard # dom-texttrack-language-dev |

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

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


TextTrack: id property - Web APIs

TextTrack: id property
======================

The **`id`** read-only property of the `TextTrack` interface returns the ID of the track if it has one.

Value
-----

A string containing the ID, or an empty string.

Examples
--------

In the following example the value of `id` is printed to the console.

```js
const video = document.querySelector("video");
const track = video.addTextTrack("captions", "Captions", "en");
track.mode = "showing";
console.log(track.id);
```

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

| Specification |
| --- |
| HTML Standard # dom-texttrack-id-dev |

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

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


TextTrack: label property - Web APIs

TextTrack: label property
=========================

The **`label`** read-only property of the `TextTrack` interface returns a human-readable label for the text track, if it is available.

Value
-----

A string containing the `label`, or an empty string.

Examples
--------

In the following example the value of `label` is printed to the console.

```js
let video = document.querySelector("video");
let track = video.addTextTrack("captions", "Captions", "en");
track.mode = "showing";
console.log(track.label);
```

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

| Specification |
| --- |
| HTML Standard # dom-texttrack-label-dev |

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

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


XRViewport: x property - Web APIs

XRViewport: x property
======================

 The read-only `XRViewport` interface's
 **`x`** property indicates the offset from the left edge of
 the destination surface (typically a `XRWebGLLayer` to the left edge of
 the viewport within the surface into which WebXR content is to be rendered. The
 viewport's `y` property identifies the `y`
 component of the origin, and its is given by the `width` and `height` properties.

Value
-----

 The offset from the left edge of the rendering surface to the left edge of the
 viewport, in pixels.

Examples
--------

See the main `XRViewport` page for examples.

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

| Specification |
| --- |
| WebXR Device API # dom-xrviewport-x |

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

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


XRViewport: height property - Web APIs

XRViewport: height property
===========================

 The read-only `XRViewport` property
 **`height`** specifies the height, in pixels, of the viewport
 onto the drawing surface within which the WebXR view is to be rendered. Along
 with `width` and the origin point given by
 `x` and `y`, this defines the
 area within which rendered content will be drawn.

Value
-----

The viewport's height in pixels.

Examples
--------

See the main `XRViewport` page for examples.

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

| Specification |
| --- |
| WebXR Device API # dom-xrviewport-height |

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

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


XRViewport: y property - Web APIs

XRViewport: y property
======================

 The read-only `XRViewport` interface's
 **`y`** property indicates the offset from the bottom edge of
 the destination surface (typically a `XRWebGLLayer` to the bottom edge of
 the viewport within the surface into which WebXR content is to be rendered. The
 viewport's `x` property identifies the `x`
 component of the origin, and its is given by the `width` and `height` properties.

Value
-----

 The offset from the bottom edge of the rendering surface to the bottom edge of the
 viewport, in pixels.

**Note:** Although other web APIs typically consider the `y`
 axis to begin at the top and grow larger progressing downward, WebGL reverses this,
 with `y` growing larger as it goes upward on the screen.

Examples
--------

See the main `XRViewport` page for examples.

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

| Specification |
| --- |
| WebXR Device API # dom-xrviewport-y |

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

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


XRViewport: width property - Web APIs

XRViewport: width property
==========================

 The read-only `XRViewport` property
 **`width`** specifies the width of the viewport, in pixels,
 onto the drawing surface the 3D scene is to be rendered into. This is defined
 using this property along with the viewport's `height`
 and its origin given by its properties `x` and
 `y`.

Value
-----

The viewport's width in pixels.

Examples
--------

See the main `XRViewport` page for examples.

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

| Specification |
| --- |
| WebXR Device API # dom-xrviewport-width |

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

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


Range: Range() constructor - Web APIs

Range: Range() constructor
==========================

 The **`Range()`** constructor returns a newly created
 `Range` object whose start and end is the global `Document`
 object.

Syntax
------

```js
new Range()
```

### Parameters

None.

Examples
--------

 In this example we create a new range with the `Range()` constructor, and
 set its beginning and end positions using the `Range.setStartBefore()` and
 `Range.setEndAfter()` methods. We then select the range using
 `window.getSelection()` and `Selection.addRange()`.

### HTML

```html
<p>First paragraph.</p>
<p>Second paragraph.</p>
<p>Third paragraph.</p>
<p>Fourth paragraph.</p>
```

### JavaScript

```js
const paragraphs = document.querySelectorAll("p");

// Create new range
const range = new Range();

// Start range at second paragraph
range.setStartBefore(paragraphs[1]);

// End range at third paragraph
range.setEndAfter(paragraphs[2]);

// Get window selection
const selection = window.getSelection();

// Add range to window selection
selection.addRange(range);
```

### Result

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-range-range② |

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

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

See also
--------

* The DOM interfaces index
* `Document.createRange()`


Range: getClientRects() method - Web APIs

Range: getClientRects() method
==============================

 The **`Range.getClientRects()`** method returns a list of `DOMRect` objects representing the area of the screen occupied by the range. This is created by aggregating the results of calls to
 `Element.getClientRects()` for all the elements in the range.

Syntax
------

```js
getClientRects()
```

### Parameters

None.

### Return value

An iterable sequence of `DOMRect` objects.

Examples
--------

### Logging selected client rect sizes

#### HTML

```html
<div></div>
<pre id="output"></pre>
```

#### CSS

```css
div {
  height: 80px;
  width: 200px;
  background-color: blue;
}
```

#### JavaScript

```js
const range = document.createRange();
range.selectNode(document.querySelector("div"));
rectList = range.getClientRects();

const output = document.querySelector("#output");
for (const rect of rectList) {
  output.textContent = `${output.textContent}\n${rect.width}:${rect.height}`;
}
```

#### Result

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

| Specification |
| --- |
| CSSOM View Module # dom-range-getclientrects |

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

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

See also
--------

* `Range`


Range: toString() method - Web APIs

Range: toString() method
========================

 The **`Range.toString()`** method is a stringifier returning
 the text of the `Range`.

 Alerting the contents of a `Range` makes an implicit
 `toString()` call, so comparing range and text through an alert dialog is
 ineffective.

Syntax
------

```js
toString()
```

### Parameters

None.

### Return value

A string.

Examples
--------

### HTML

```html
<p>
  This example logs <em>everything</em> between the emphasized <em>words</em>.
  Look at the output below.
</p>
<p id="log"></p>
```

### JavaScript

```js
const range = document.createRange();

range.setStartBefore(document.getElementsByTagName("em").item(0), 0);
range.setEndAfter(document.getElementsByTagName("em").item(1), 0);
document.getElementById("log").textContent = range.toString();
```

### Result

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

| Specification |
| --- |
| DOM Standard # dom-range-stringifier |

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

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

See also
--------

* The DOM interfaces index


Range: compareNode() method - Web APIs

Range: compareNode() 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.

 The **`Range.compareNode()`** returns a constant indicating the
 position of the `Node`.

The possible values are:

`NODE_BEFORE` (`0`)

Node starts before the Range

`NODE_AFTER` (`1`)

Node ends after the Range

`NODE_BEFORE_AND_AFTER` (`2`)

Node starts before and ends after the Range

`NODE_INSIDE` (`3`)

 Node starts after and ends before the Range, i.e. the Node is completely selected by
 the Range.

**Warning:** This method has been removed from Gecko 1.9 and
 will not exist in future versions of Firefox, which was the only browser implementing
 it; you should switch to `Range.compareBoundaryPoints()` as soon as
 possible.

The following function can be used as replacement:

```js
function rangeCompareNode(range, node) {
  const nodeRange = node.ownerDocument.createRange();
  try {
    nodeRange.selectNode(node);
  } catch (e) {
    nodeRange.selectNodeContents(node);
  }
  const nodeIsBefore =
    range.compareBoundaryPoints(Range.START\_TO\_START, nodeRange) === 1;
  const nodeIsAfter =
    range.compareBoundaryPoints(Range.END\_TO\_END, nodeRange) === -1;

  if (nodeIsBefore && !nodeIsAfter) return 0;
  if (!nodeIsBefore && nodeIsAfter) return 1;
  if (nodeIsBefore && nodeIsAfter) return 2;

  return 3;
}
```

Syntax
------

```js
compareNode(referenceNode)
```

### Parameters

`referenceNode`

The `Node` to compare with the `Range`.

### Return value

A constant indicating the position of the `Node`.

Examples
--------

```js
range = document.createRange();
range.selectNode(document.getElementsByTagName("div").item(0));
returnValue = range.compareNode(document.getElementsByTagName("p").item(0));
```

Notes
-----

 This method is obsolete; you should use the W3C DOM
 `Range.compareBoundaryPoints()` method.

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

This method is not standard and therefore not part of any specification.

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

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

See also
--------

* The DOM interfaces index


Range: compareBoundaryPoints() method - Web APIs

Range: compareBoundaryPoints() method
=====================================

 The
 **`Range.compareBoundaryPoints()`** method compares the
 boundary points of the `Range` with those of another range.

Syntax
------

```js
compareBoundaryPoints(how, sourceRange)
```

### Parameters

`how`

A constant describing the comparison method:

* `Range.END_TO_END` compares the end boundary-point of
 *sourceRange* to the end boundary-point of `Range`.
* `Range.END_TO_START` compares the end boundary-point of
 *sourceRange* to the start boundary-point of `Range`.
* `Range.START_TO_END` compares the start boundary-point of
 *sourceRange* to the end boundary-point of `Range`.
* `Range.START_TO_START` compares the start boundary-point of
 *sourceRange* to the start boundary-point of `Range`.

`sourceRange`

A `Range` to compare boundary points with the range.

### Return value

 A number, `-1`, `0`, or `1`, indicating whether the
 corresponding boundary-point of the `Range` is respectively before, equal
 to, or after the corresponding boundary-point of *sourceRange*.

### Exceptions

`NotSupportedError` `DOMException`

Thrown if the value of the `how` parameter is invalid.

Examples
--------

```js
const range = document.createRange();
range.selectNode(document.querySelector("div"));
const sourceRange = document.createRange();
sourceRange.selectNode(document.getElementsByTagName("div")[1]);
const compare = range.compareBoundaryPoints(Range.START\_TO\_END, sourceRange);
```

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

| Specification |
| --- |
| DOM Standard # dom-range-compareboundarypoints |

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

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

See also
--------

* The DOM interfaces index


Range: selectNode() method - Web APIs

Range: selectNode() method
==========================

 The **`Range.selectNode()`** method sets the
 `Range` to contain the `Node` and its contents. The parent
 `Node` of the start and end of the `Range` will be the same as
 the parent of the *referenceNode*.

Syntax
------

```js
selectNode(referenceNode)
```

### Parameters

`referenceNode`

The `Node` to select within a `Range`.

### Return value

None (`undefined`).

Examples
--------

```js
let range = document.createRange();
let referenceNode = document.getElementsByTagName("div").item(0);

range.selectNode(referenceNode);
```

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

| Specification |
| --- |
| DOM Standard # dom-range-selectnode |

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

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

See also
--------

* The DOM interfaces index


Range: extractContents() method - Web APIs

Range: extractContents() method
===============================

 The **`Range.extractContents()`** method moves contents of the
 `Range` from the document tree into a `DocumentFragment`.

 Event listeners added using DOM Events are not retained during extraction. HTML
 attribute events are retained or duplicated as they are for the
 `Node.cloneNode()` method. HTML `id` attributes are also cloned,
 which can lead to an invalid document if a partially-selected node is extracted and
 appended to the document.

 Partially selected nodes are cloned to include the parent tags necessary to make the
 document fragment valid.

Syntax
------

```js
extractContents()
```

### Parameters

None.

### Return value

A `DocumentFragment` object.

Examples
--------

### Basic example

```js
const range = document.createRange();
range.selectNode(document.getElementsByTagName("div").item(0));
const documentFragment = range.extractContents();
document.body.appendChild(documentFragment);
```

### Moving items between containers

 This example lets you move items between two containers. Select one or more item, and
 then click "swap" to move them to the opposite container.

#### HTML

```html
<p id="list1">123456</p>
<button id="swap">Swap selected item(s)</button>
<p id="list2">abcdef</p>
```

#### CSS

```css
body {
  pointer-events: none;
}

p {
  border: 1px solid;
  font-size: 2em;
  padding: 0.3em;
}

button {
  font-size: 1.2em;
  padding: 0.5em;
  pointer-events: auto;
}
```

#### JavaScript

```js
const list1 = document.getElementById("list1");
const list2 = document.getElementById("list2");
const button = document.getElementById("swap");

button.addEventListener("click", (e) => {
  selection = window.getSelection();

  for (let i = 0; i < selection.rangeCount; i++) {
    const range = selection.getRangeAt(i);

    if (
      range.commonAncestorContainer === list1 ||
      range.commonAncestorContainer.parentNode === list1
    ) {
      const documentFragment = range.extractContents();
      list2.appendChild(documentFragment);
    } else if (
      range.commonAncestorContainer === list2 ||
      range.commonAncestorContainer.parentNode === list2
    ) {
      const documentFragment = range.extractContents();
      list1.appendChild(documentFragment);
    }
  }
});
```

#### Result

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

| Specification |
| --- |
| DOM Standard # dom-range-extractcontents |

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

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

See also
--------

* The DOM interfaces index


Range: surroundContents() method - Web APIs

Range: surroundContents() method
================================

 The **`Range.surroundContents()`** method moves content of the
 `Range` into a new node, placing the new node at the start of the
 specified range.

 This method is nearly equivalent to
 `newNode.appendChild(range.extractContents()); range.insertNode(newNode)`.
 After surrounding, the boundary points of the `range` include
 `newNode`.

 An exception will be thrown, however, if the `Range` splits a non-`Text` node with only one of its boundary points. That is, unlike the
 alternative above, if there are partially selected nodes, they will not be cloned and
 instead the operation will fail.

Syntax
------

```js
surroundContents(newParent)
```

### Parameters

`newParent`

A `Node` with which to surround the contents.

### Return value

None (`undefined`).

Examples
--------

### HTML

```html
<span class="header-text">Put this in a headline</span>
```

### JavaScript

```js
const range = document.createRange();
const newParent = document.createElement("h1");

range.selectNode(document.querySelector(".header-text"));
range.surroundContents(newParent);
```

### Result

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

| Specification |
| --- |
| DOM Standard # dom-range-surroundcontents |

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

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

See also
--------

* The DOM interfaces index


Range: intersectsNode() method - Web APIs

Range: intersectsNode() method
==============================

 The **`Range.intersectsNode()`** method returns a boolean
 indicating whether the given `Node` intersects the `Range`.

Syntax
------

```js
intersectsNode(referenceNode)
```

### Parameters

`referenceNode`

The `Node` to compare with the `Range`.

### Return value

A boolean.

Examples
--------

```js
const range = document.createRange();

range.selectNode(document.getElementsByTagName("div").item(0));
const intersectingNode = range.intersectsNode(
  document.getElementsByTagName("p").item(0),
);
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-range-intersectsnode① |

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

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

See also
--------

* The DOM interfaces index


Range: startOffset property - Web APIs

Range: startOffset property
===========================

 The **`Range.startOffset`** read-only property returns a number
 representing where in the `startContainer` the `Range` starts.

 If the `startContainer` is a `Node` of type
 `Text`, `Comment`, or `CDATASection`, then the
 offset is the number of characters from the start of the `startContainer` to
 the boundary point of the `Range`. For other `Node` types, the
 `startOffset` is the number of child nodes between the start of the
 `startContainer` and the boundary point of the `Range`.

 To change the `startOffset` of a `Range`, use the
 `Range.setStart` method.

Value
-----

A number.

Examples
--------

```js
const range = document.createRange();
range.setStart(startNode, startOffset);
range.setEnd(endNode, endOffset);
const startRangeOffset = range.startOffset;
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-range-startoffset① |

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

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

See also
--------

* The DOM interfaces index


Range: collapse() method - Web APIs

Range: collapse() method
========================

 The **`Range.collapse()`** method collapses the
 `Range` to one of its boundary points.

 A collapsed `Range` is empty, containing no content, specifying a
 single-point in a DOM tree. To determine if a `Range` is already collapsed,
 see the `Range.collapsed` property.

Syntax
------

```js
collapse()
collapse(toStart)
```

### Parameters

`toStart` Optional

 A boolean value: `true` collapses the `Range`
 to its start, `false` to its end. If omitted, it defaults to
 `false`
Experimental
.

### Return value

None (`undefined`).

Examples
--------

```js
const range = document.createRange();

const referenceNode = document.getElementsByTagName("div").item(0);
range.selectNode(referenceNode);
range.collapse(true);
```

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

| Specification |
| --- |
| DOM Standard # dom-range-collapse |

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

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

See also
--------

* The DOM interfaces index


Range: selectNodeContents() method - Web APIs

Range: selectNodeContents() method
==================================

The **`Range.selectNodeContents()`** method sets the `Range` to contain the contents of a `Node`.

 The parent `Node` of the start and end of the `Range` will be the
 reference node. The `startOffset` is 0, and the `endOffset` is the
 number of child `Node`s or number of characters contained in the reference
 node.

Syntax
------

```js
selectNodeContents(referenceNode)
```

### Parameters

`referenceNode`

The `Node` whose contents will be selected within a `Range`.

### Return value

None (`undefined`).

Examples
--------

```js
const range = document.createRange();
const referenceNode = document.querySelector("div");
range.selectNodeContents(referenceNode);
```

### Live sample

 This example lets the user select and deselect a paragraph with buttons.
 `Document.createRange()`, `Range.selectNodeContents()`, and
 `Selection.addRange()` are used to select the content.
 `Window.getSelection()` and `Selection.removeAllRanges()` are
 used to deselect it.

#### HTML

```html
<p id="p">
  <strong>Use the buttons below</strong> to select or deselect the contents of
  this paragraph.
</p>
<button id="select-button">Select paragraph</button>
<button id="deselect-button">Deselect paragraph</button>
```

#### JavaScript

```js
const p = document.getElementById("p");
const selectButton = document.getElementById("select-button");
const deselectButton = document.getElementById("deselect-button");

selectButton.addEventListener("click", (e) => {
  // Clear any current selection
  const selection = window.getSelection();
  selection.removeAllRanges();

  // Select paragraph
  const range = document.createRange();
  range.selectNodeContents(p);
  selection.addRange(range);
});

deselectButton.addEventListener("click", (e) => {
  const selection = window.getSelection();
  selection.removeAllRanges();
});
```

#### Result

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

| Specification |
| --- |
| DOM Standard # dom-range-selectnodecontents |

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

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

See also
--------

* The DOM interfaces index


Range: setStart() method - Web APIs

Range: setStart() method
========================

 The **`Range.setStart()`** method sets the start position of a
 `Range`.

 If the `startNode` is a `Node` of type `Text`,
 `Comment`, or `CDataSection`, then `startOffset` is
 the number of characters from the start of `startNode`. For other
 `Node` types, `startOffset` is the number of child nodes between
 the start of the `startNode`.

 Setting the start point below (lower in the document) the end point will result in a
 collapsed range with the start and end points both set to the specified start position.

Syntax
------

```js
setStart(startNode, startOffset)
```

### Parameters

`startNode`

The `Node` where the `Range` should start.

`startOffset`

 An integer greater than or equal to zero representing the offset for the start of
 the `Range` from the start of `startNode`.

### Return value

None (`undefined`).

Examples
--------

### Highlight part of an element

 This example uses the `Range.setStart()` and `Range.setEnd()`
 methods to add part of an address to a range. The selected range is then highlighted
 using `Range.surroundContents()`.

 The address contains nine nodes: five text nodes, and four `<br>`
 elements.

#### HTML

```html
<p id="address">
  Wyatt Earp<br />
  101 E. Main St.<br />
  Dodge City, KS<br />
  67801<br />
  USA
</p>

<hr />
<p>Nodes in the original address:</p>
<ol id="log"></ol>
```

#### JavaScript

```js
const address = document.getElementById("address");
const log = document.getElementById("log");

// Log info
address.childNodes.forEach((node) => {
  const li = document.createElement("li");
  li.textContent = `${node.nodeName}, ${node.nodeValue}`;
  log.appendChild(li);
});

// Highlight the street and city
const startOffset = 2; // Start at third node: 101 E. Main St.
const endOffset = 5; // End at fifth node: Dodge City, KS
const range = document.createRange();
range.setStart(address, startOffset);
range.setEnd(address, endOffset);

const mark = document.createElement("mark");
range.surroundContents(mark);
```

#### Result

### Get characters from a text node

 This example uses the `Range.setStart()` and `Range.setEnd()`
 methods to define the contents of a range. The resulting range contains the first
 through fifth characters within a text node.

#### HTML

```html
<p id="content">0123456789</p>
<p id="log"></p>
```

#### JavaScript

```js
const element = document.getElementById("content");
const textNode = element.childNodes[0];
const range = document.createRange();
range.setStart(textNode, 0); // Start at first character
range.setEnd(textNode, 5); // End at fifth character
document.getElementById("log").textContent = range;
```

#### Result

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

| Specification |
| --- |
| DOM Standard # dom-range-setstart |

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

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

See also
--------

* The DOM interfaces index


Range: setStartAfter() method - Web APIs

Range: setStartAfter() method
=============================

 The **`Range.setStartAfter()`** method sets the start position
 of a `Range` relative to a `Node`. The parent
 `Node` of the start of the `Range` will be the same as that
 for the `referenceNode`.

Syntax
------

```js
setStartAfter(referenceNode)
```

### Parameters

`referenceNode`

The `Node` to start the `Range` after.

### Return value

None (`undefined`).

Examples
--------

```js
const range = document.createRange();
const referenceNode = document.getElementsByTagName("div").item(0);

range.setStartAfter(referenceNode);
```

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

| Specification |
| --- |
| DOM Standard # dom-range-setstartafter |

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

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

See also
--------

* The DOM interfaces index


Range: setEndBefore() method - Web APIs

Range: setEndBefore() method
============================

 The **`Range.setEndBefore()`** method sets the end position of
 a `Range` relative to another `Node`. The parent
 `Node` of end of the `Range` will be the same as that for the
 `referenceNode`.

Syntax
------

```js
setEndBefore(referenceNode)
```

### Parameters

`referenceNode`

The `Node` to end the `Range` before.

### Return value

None (`undefined`).

Examples
--------

```js
const range = document.createRange();
const referenceNode = document.getElementsByTagName("div").item(0);

range.setEndBefore(referenceNode);
```

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

| Specification |
| --- |
| DOM Standard # dom-range-setendbefore |

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

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

See also
--------

* The DOM interfaces index


Range: insertNode() method - Web APIs

Range: insertNode() method
==========================

 The **`Range.insertNode()`** method inserts a node at the start
 of the `Range`.

 The new node is inserted at the start boundary point of the `Range`. If the
 new node is to be added to a text `Node`, that `Node` is split
 at the insertion point, and the insertion occurs between the two text nodes.

 If the new node is a document fragment, the children of the document fragment are
 inserted instead.

Syntax
------

```js
insertNode(newNode)
```

### Parameters

`newNode`

The `Node` to insert at the start of the `range`.

### Return value

None (`undefined`).

Examples
--------

```js
range = document.createRange();
newNode = document.createElement("p");
newNode.appendChild(document.createTextNode("New Node Inserted Here"));
range.selectNode(document.getElementsByTagName("div").item(0));
range.insertNode(newNode);
```

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

| Specification |
| --- |
| DOM Standard # dom-range-insertnode |

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

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

See also
--------

* The DOM interfaces index


Range: setEnd() method - Web APIs

Range: setEnd() method
======================

 The **`Range.setEnd()`** method sets the end position of a `Range` to be located at the given offset into the specified node x.Setting
 the end point above (higher in the document) than the start point will result in a
 collapsed range with the start and end points both set to the specified end position.

Syntax
------

```js
setEnd(endNode, endOffset)
```

### Parameters

`endNode`

The `Node` inside which the `Range` should end.

`endOffset`

An integer greater than or equal to zero representing the offset for the end of the `Range` from the start of `endNode`.

### Return value

None (`undefined`).

### Exceptions

`InvalidNodeTypeError` `DOMException`

The node specified by `endNode` is a doctype node; range endpoints cannot be located inside a doctype node.

`IndexSizeError` `DOMException`

The value specified by `endOffset` is either greater than or equal to the length of the node or is less than zero.

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

 If the `endNode` is a `Node` of type `Text`,
 `Comment`, or `CDataSection`, then `endOffset` is
 the number of characters from the start of `endNode`. For other
 `Node` types, `endOffset` is the number of child nodes between
 the start of the `endNode`.

Examples
--------

```js
const range = document.createRange();
const endNode = document.getElementsByTagName("p").item(3);
const endOffset = endNode.childNodes.length;
range.setEnd(endNode, endOffset);
```

**Note:** `setEnd()` is commonly used in conjunction with
 `setStart()` to fully configure a range.

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

| Specification |
| --- |
| DOM Standard # dom-range-setend |

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

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

See also
--------

* The DOM interfaces index


Range: endOffset property - Web APIs

Range: endOffset property
=========================

 The **`Range.endOffset`** read-only property returns a number
 representing where in the `Range.endContainer` the `Range`
 ends.

 If the `endContainer` is a `Node` of type `Text`,
 `Comment`, or `CDATASection`, then the offset is the number of
 characters from the start of the `endContainer` to the boundary point of the
 `Range`. For other `Node` types, the `endOffset` is
 the number of child nodes between the start of the `endContainer` and the
 boundary point of the `Range`. This property is read-only. To change the
 `endOffset` of a `Range`, use one of the
 `Range.setEnd` methods.

Value
-----

A number.

Examples
--------

```js
const range = document.createRange();

range.setStart(startNode, startOffset);
range.setEnd(endNode, endOffset);
endRangeOffset = range.endOffset;
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-range-endoffset① |

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

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

See also
--------

* The DOM interfaces index


Range: getBoundingClientRect() method - Web APIs

Range: getBoundingClientRect() method
=====================================

 The **`Range.getBoundingClientRect()`** method returns a `DOMRect` object that bounds the contents of the range; this is a rectangle
 enclosing the union of the bounding rectangles for all the elements in the range.

 This method is useful for determining the viewport coordinates of the cursor or
 selection inside a text box. See `Element.getBoundingClientRect()` for
 details on the returned value.

Syntax
------

```js
getBoundingClientRect()
```

### Parameters

None.

### Return value

A `DOMRect` object that encloses the union of the bounding rectangles for all elements in the range.

Examples
--------

### HTML

```html
<div id="highlight"></div>
<p>
  This example positions a "highlight" rectangle behind the contents of a range.
  The range's content <em>starts here</em> and continues on until it
  <em>ends here</em>. The bounding client rectangle contains everything selected
  in the range.
</p>
```

### CSS

```css
#highlight {
  background: yellow;
  position: absolute;
  z-index: -1;
}

p {
  width: 200px;
}
```

### JavaScript

```js
const range = document.createRange();
range.setStartBefore(document.getElementsByTagName("em").item(0));
range.setEndAfter(document.getElementsByTagName("em").item(1));

const clientRect = range.getBoundingClientRect();
const highlight = document.getElementById("highlight");
highlight.style.left = `${clientRect.x}px`;
highlight.style.top = `${clientRect.y}px`;
highlight.style.width = `${clientRect.width}px`;
highlight.style.height = `${clientRect.height}px`;
```

### Result

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

| Specification |
| --- |
| CSSOM View Module # dom-range-getboundingclientrect |

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

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

See also
--------

* `Range.getClientRects()` - finer-grained result for non-rectangular
 ranges (e.g., when the selection wraps onto the next line);
* `Element.getBoundingClientRect()`
* `Document.caretPositionFromPoint()` - to get the (node, offset) from
 viewport coordinates.


Range: createContextualFragment() method - Web APIs

Range: createContextualFragment() method
========================================

 The **`Range.createContextualFragment()`** method returns a
 `DocumentFragment` by invoking the HTML fragment parsing algorithm or the
 XML fragment parsing algorithm with the start of the range (the *parent* of the
 selected node) as the context node. The HTML fragment parsing algorithm is used if the
 range belongs to a `Document` whose HTMLness bit is set. In the HTML case, if
 the context node would be `html`, for historical reasons the fragment parsing
 algorithm is invoked with `body` as the context instead.

Syntax
------

```js
createContextualFragment(tagString)
```

### Parameters

`tagString`

Text that contains text and tags to be converted to a document fragment.

### Return value

A `DocumentFragment` object.

Examples
--------

```js
const tagString = "<div>I am a div node</div>";
const range = document.createRange();

// Make the parent of the first div in the document become the context node
range.selectNode(document.getElementsByTagName("div").item(0));
const documentFragment = range.createContextualFragment(tagString);
document.body.appendChild(documentFragment);
```

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

| Specification |
| --- |
| DOM Parsing and Serialization # ref-for-dom-range-createcontextualfragment-2 |

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

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

See also
--------

* The DOM interfaces index


Range: setStartBefore() method - Web APIs

Range: setStartBefore() method
==============================

 The **`Range.setStartBefore()`** method sets the start position
 of a `Range` relative to another `Node`. The parent
 `Node` of the start of the `Range` will be the same as that
 for the `referenceNode`.

Syntax
------

```js
setStartBefore(referenceNode)
```

### Parameters

`referenceNode`

The `Node` before which the `Range` should start.

### Return value

None (`undefined`).

Examples
--------

```js
const range = document.createRange();
const referenceNode = document.getElementsByTagName("div").item(0);

range.setStartBefore(referenceNode);
```

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

| Specification |
| --- |
| DOM Standard # dom-range-setstartbefore |

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

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

See also
--------

* The DOM interfaces index


Range: setEndAfter() method - Web APIs

Range: setEndAfter() method
===========================

 The **`Range.setEndAfter()`** method sets the end position of a
 `Range` relative to another `Node`. The parent
 `Node` of end of the `Range` will be the same as that for the
 `referenceNode`.

Syntax
------

```js
setEndAfter(referenceNode)
```

### Parameters

`referenceNode`

The `Node` to end the `Range` after.

### Return value

None (`undefined`).

Examples
--------

```js
const range = document.createRange();
const referenceNode = document.getElementsByTagName("div").item(0);

range.setEndAfter(referenceNode);
```

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

| Specification |
| --- |
| DOM Standard # dom-range-setendafter |

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

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

See also
--------

* The DOM interfaces index


Range: commonAncestorContainer property - Web APIs

Range: commonAncestorContainer property
=======================================

 The **`Range.commonAncestorContainer`** read-only property
 returns the deepest — or furthest down the document tree — `Node` that
 contains both boundary points of the `Range`. This means that if
 `Range.startContainer` and `Range.endContainer` both refer to
 the same node, this node is the **common ancestor container**.

 Since a `Range` need not be continuous, and may also partially select nodes,
 this is a convenient way to find a `Node` which encloses a
 `Range`.

 This property is read-only. To change the ancestor container of a `Node`,
 consider using the various methods available to set the start and end positions of the
 `Range`, such as `Range.setStart()` and
 `Range.setEnd()`.

Value
-----

A `Node` object.

Examples
--------

 In this example, we create an event listener to handle `pointerup` events on
 a list. The listener gets the common ancestors of each piece of selected text and
 triggers an animation to highlight them.

### HTML

```html
<ul>
  <li>
    Strings
    <ul>
      <li>Cello</li>
      <li>
        Violin
        <ul>
          <li>First Chair</li>
          <li>Second Chair</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>
    Woodwinds
    <ul>
      <li>Clarinet</li>
      <li>Oboe</li>
    </ul>
  </li>
</ul>
```

### CSS

 The `.highlight` class created below uses a set of CSS
 `@keyframes` to animate a fading outline.

```css
.highlight {
  animation: highlight linear 1s;
}

@keyframes highlight {
  from {
    outline: 1px solid #f00f;
  }
  to {
    outline: 1px solid #f000;
  }
}
```

```
body {
  padding: 1px;
}
```

### JavaScript

```js
document.addEventListener("pointerup", (e) => {
  const selection = window.getSelection();

  if (selection.type === "Range") {
    for (let i = 0; i < selection.rangeCount; i++) {
      const range = selection.getRangeAt(i);
      playAnimation(range.commonAncestorContainer);
    }
  }
});

function playAnimation(el) {
  if (el.nodeType === Node.TEXT\_NODE) {
    el = el.parentNode;
  }

  el.classList.remove("highlight");
  setTimeout(() => {
    el.classList.add("highlight");
  }, 0);
}
```

### Result

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-range-commonancestorcontainer② |

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

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

See also
--------

* The DOM interfaces index


Range: detach() method - Web APIs

Range: detach() method
======================

 The **`Range.detach()`** method does nothing. It used to
 disable the `Range` object and enable the browser to release associated
 resources. The method has been kept for compatibility.

Syntax
------

```js
detach()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

```js
const range = document.createRange();

range.selectNode(document.getElementsByTagName("div").item(0));
range.detach();
```

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

| Specification |
| --- |
| DOM Standard # dom-range-detach |

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

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

See also
--------

* The DOM interfaces index


Range: comparePoint() method - Web APIs

Range: comparePoint() method
============================

 The **`Range.comparePoint()`** method returns `-1`,
 `0`, or `1` depending on whether the `referenceNode` is
 before, the same as, or after the `Range`.

 If the *reference node* is a `Node` of type `Text`,
 `Comment`, or `CDATASection`, then offset is the number of
 characters from the start of *reference node*. For other `Node`
 types, offset is the number of child nodes between the start of the *reference
node*.

Syntax
------

```js
comparePoint(referenceNode, offset)
```

### Parameters

`referenceNode`

The `Node` to compare with the `Range`.

`offset`

 An integer greater than or equal to zero representing the offset inside the
 *referenceNode*.

### Return value

Returns `-1`, `0`, or `1`.

Examples
--------

```js
range = document.createRange();
range.selectNode(document.getElementsByTagName("div").item(0));
returnValue = range.comparePoint(document.getElementsByTagName("p").item(0), 1);
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-range-comparepoint① |

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

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

See also
--------

* The DOM interfaces index


Range: startContainer property - Web APIs

Range: startContainer property
==============================

 The **`Range.startContainer`** read-only property returns the
 `Node` within which the `Range` starts. To change the start
 position of a node, use one of the `Range.setStart()` methods.

Value
-----

A `Node` object.

Examples
--------

```js
range = document.createRange();
range.setStart(startNode, startOffset);
range.setEnd(endNode, endOffset);
startRangeNode = range.startContainer;
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-range-startcontainer① |

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

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

See also
--------

* The DOM interfaces index


Range: collapsed property - Web APIs

Range: collapsed property
=========================

 The **`Range.collapsed`** read-only property returns a
 boolean flag indicating whether the start and end points of the
 `Range` are at the same position. It returns `true` if the start
 and end boundary points of the `Range` are the same point in the DOM,
 `false` if not.

 A collapsed `Range` is empty (containing no content), and specifies a
 single point in a DOM tree. To collapse a range, see the `Range.collapse()`
 method.

Value
-----

A boolean.

Examples
--------

```js
let range = document.createRange();

range.setStart(startNode, startOffset);
range.setEnd(endNode, endOffset);
isCollapsed = range.collapsed;
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-range-collapsed① |

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

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

See also
--------

* The DOM interfaces index


Range: deleteContents() method - Web APIs

Range: deleteContents() method
==============================

 The **`Range.deleteContents()`** method removes the contents of
 the `Range` from the `Document`.

 Unlike `Range.extractContents()`, this method does not return a
 `DocumentFragment` containing the deleted content.

Syntax
------

```js
deleteContents()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

```js
range = document.createRange();
range.selectNode(document.getElementsByTagName("div").item(0));
range.deleteContents();
```

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

| Specification |
| --- |
| DOM Standard # dom-range-deletecontents |

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

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

See also
--------

* The DOM interfaces index


Range: isPointInRange() method - Web APIs

Range: isPointInRange() method
==============================

 The **`Range.isPointInRange()`** method returns a boolean
 indicating whether the given point is in the `Range`. It returns
 `true` if the point (cursor position) at `offset` within
 `ReferenceNode` is within this range.

Syntax
------

```js
isPointInRange(referenceNode, offset)
```

### Parameters

`referenceNode`

The `Node` to compare with the `Range`.

`offset`

 The offset into `Node` of the point to compare with the
 `Range`.

### Return value

A boolean.

Examples
--------

```js
range = document.createRange();
range.selectNode(document.getElementsByTagName("div").item(0));
bool = range.isPointInRange(document.getElementsByTagName("p").item(0), 1);
```

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

| Specification |
| --- |
| DOM Standard # dom-range-ispointinrange |

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

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

See also
--------

* The DOM interfaces index


Range: endContainer property - Web APIs

Range: endContainer property
============================

 The **`Range.endContainer`** read-only property returns the
 `Node` within which the `Range` ends. To change the end
 position of a node, use the `Range.setEnd()` method or a similar one.

Value
-----

A `Node` object.

Examples
--------

```js
const range = document.createRange();

range.setStart(startNode, startOffset);
range.setEnd(endNode, endOffset);
endRangeNode = range.endContainer;
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-range-endcontainer① |

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

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

See also
--------

* The DOM interfaces index


Range: cloneRange() method - Web APIs

Range: cloneRange() method
==========================

 The **`Range.cloneRange()`** method returns a
 `Range` object with boundary points identical to the cloned
 `Range`.

 The returned clone is copied by value, not reference, so a change in either
 `Range` does not affect the other.

Syntax
------

```js
cloneRange()
```

### Parameters

None.

### Return value

A `Range` object.

Examples
--------

```js
range = document.createRange();
range.selectNode(document.getElementsByTagName("div").item(0));
clone = range.cloneRange();
```

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

| Specification |
| --- |
| DOM Standard # dom-range-clonerange |

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

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

See also
--------

* The DOM interfaces index


Range: cloneContents() method - Web APIs

Range: cloneContents() method
=============================

 The **`Range.cloneContents()`** returns a `DocumentFragment` copying the objects of type `Node`
 included in the `Range`.

 Event listeners added using `addEventListener()`
 are not copied during cloning. HTML attribute events are duplicated as they are
 for the `Node.cloneNode()` method. HTML `id` attributes
 are also cloned, which can lead to an invalid document through cloning.

 Partially selected nodes include the parent tags necessary to make the document
 fragment valid.

Syntax
------

```js
cloneContents()
```

### Parameters

None.

### Return value

A `DocumentFragment` object.

Examples
--------

```js
range = document.createRange();
range.selectNode(document.getElementsByTagName("div").item(0));
documentFragment = range.cloneContents();
document.body.appendChild(documentFragment);
```

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

| Specification |
| --- |
| DOM Standard # dom-range-clonecontents |

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

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

See also
--------

* The DOM interfaces index


IdentityCredential: token property - Web APIs

IdentityCredential: token property
==================================

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

The **`token`** read-only property of the `IdentityCredential` interface returns the token used to validate the associated sign-in.

Value
-----

A string.

Examples
--------

Relying parties (RPs) can call `navigator.credentials.get()` with the `identity` option to make a request for users to sign in to the RP via an identity provider (IdP), using identity federation. A typical request would look like this:

```js
async function signIn() {
  const identityCredential = await navigator.credentials.get({
    identity: {
      providers: [
        {
          configURL: "https://accounts.idp.example/config.json",
          clientId: "\*\*\*\*\*\*\*\*",
          nonce: "\*\*\*\*\*\*",
        },
      ],
    },
  });

  console.log(identityCredential.token);
}
```

A successful `navigator.credentials.get()` call that includes an `identity` option fulfills with an `IdentityCredential` instance, which can be used to access the token used to validate the sign-in.

Check out Federated Credential Management API (FedCM) for more details on how this works. This call will start off the sign-in flow described in FedCM sign-in flow.

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

| Specification |
| --- |
| Federated Credential Management API # dom-identitycredential-token |

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

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

See also
--------

* Federated Credential Management API


SubmitEvent: SubmitEvent() constructor - Web APIs

SubmitEvent: SubmitEvent() constructor
======================================

 The **`SubmitEvent()`** constructor creates and returns a new `SubmitEvent` object,
 which is used to represent a `submit` event
 fired at an HTML form.

Syntax
------

```js
new SubmitEvent(type)
new SubmitEvent(type, options)
```

### Parameters

`type`

 A string with the name of the event.
 It is case-sensitive and browsers always set it to `submit`.

`options` Optional

An object that, *in addition of the properties defined in `Event()`*, can have the following properties:

`submitter` Optional

An `HTMLElement` object that is the submit button that triggered the form submission.

### Return value

A `SubmitEvent` object configured using the given inputs.

Examples
--------

 This code snippet locates a form in the current document, and then an HTML
 `<button>` within the form with the class `submit` on it.
 Next, a new `SubmitEvent` is created, configured with
 its `submitter` set to the identified button
 (or `null` if the button wasn't found). Then the event is sent to the form,
 telling the form that it's been submitted by the button.

```js
const form = document.querySelector("form");
const formTrigger = form.querySelector("button.submit");
const submitEvent = new SubmitEvent("submit", { submitter: formTrigger });

form.dispatchEvent(submitEvent);
```

 This is a somewhat contrived example, as you can do nearly all of this much more
 easily, but this gives you deep control over the process that can be useful.

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

| Specification |
| --- |
| HTML Standard # submitevent |

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

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


SubmitEvent: submitter property - Web APIs

SubmitEvent: submitter property
===============================

 The read-only **`submitter`** property found on
 the `SubmitEvent` interface specifies the submit button or other element
 that was invoked to cause the form to be submitted.

Value
-----

 An element, indicating the element that sent
 the `submit` event to the form. While this
 is often an `<input>` element whose `type` is `submit` or a `<button>` element whose `type` is `submit`, it could be some other element which has initiated a
 submission process.

If the submission was not triggered by a button of some kind, the value of `submitter` is `null`.

Examples
--------

See `SubmitEvent` for example code.

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

| Specification |
| --- |
| HTML Standard # the-submitevent-interface:dom-submitevent-submitter-2 |

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

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


Storage quotas and eviction criteria - Web APIs

Storage quotas and eviction criteria
====================================

Web developers can use a number of technologies to store data in the user's browser (i.e., on the local disk of the device the user is using to view the website).

The amount of data browsers allow websites to store and the mechanisms they use to delete data when that limit is reached differs between browsers.

This article describes the web technologies that can be used to store data, the quotas that browsers have in place to limit websites from storing too much data, and the mechanisms they use to delete data when needed.

How do browsers separate data from different websites?
------------------------------------------------------

Browsers store the data from websites in different places, also called buckets, to reduce the risk of users being tracked across the web. In most cases, browsers manage stored data *per origin*.

The term *origin* is therefore important to understand this article. An origin is defined by a scheme (such as HTTPS), a hostname, and a port. For example, `https://example.com` and `https://example.com/app/index.html` belong to the same origin because they have the same scheme (`https`), hostname (`example.com`), and default port.

The quotas and eviction criteria described in this article apply to an entire origin, even if this origin is used to run several websites, such as `https://example.com/site1/` and `https://example.com/site2/`.

In some cases, however, browsers can decide to further separate the data stored by an origin in different partitions, for example in cases where an origin is loaded within an `<iframe>` element in multiple different third-party origins. However, for simplicity reasons, this article assumes that data is always stored per origin.

What technologies store data in the browser?
--------------------------------------------

Web developers can use the following web technologies to store data in the browser:

| Technology | Description |
| --- | --- |
| Cookies | An HTTP cookie is a small piece of data that the web server and browser send each other to remember stateful information across page navigation. |
| Web Storage | The Web Storage API provides mechanisms for webpages to store string-only key/value pairs, including `localStorage` and `sessionStorage`. |
| IndexedDB | IndexedDB is a Web API for storing large data structures in the browser and indexing them for high-performance searching. |
| Cache API | The Cache API provides a persistent storage mechanism for HTTP request and response object pairs that's used to make webpages load faster. |
| Origin Private File System (OPFS) | OPFS provides a file system that's private to the origin of the page and can be used to read and write directories and files. |

Note that, in addition to the above, browsers will store other types of data in the browser for an origin, such as WebAssembly code caching.

Does browser-stored data persist?
---------------------------------

Data for an origin can be stored in two ways in a browser, *persistent* and *best-effort*:

* Best-effort: this is the way that data is stored by default. Best-effort data persists as long as the origin is below its quota, the device has enough storage space, and the user doesn't choose to delete the data via their browser's settings.
* Persistent: an origin can opt-in to store its data in a persistent way. Data stored this way is only evicted, or deleted, if the user chooses to, by using their browser's settings. To learn more, see When is data evicted.

The data stored in the browser by an origin is best-effort by default. When using web technologies such as IndexedDB or Cache, the data is stored transparently without asking for the user's permission. Similarly, when the browser needs to evict best-effort data, it does so without interrupting the user.

If, for any reason, developers need persistent storage (e.g., when building a web app that relies on critical data that isn't persisted anywhere else), they can do so by using the `navigator.storage.persist()` method of the Storage API.

In Firefox, when a site chooses to use persistent storage, the user is notified with a UI popup that their permission is requested.

Safari and most Chromium-based browsers, such as Chrome or Edge, automatically approve or deny the request based on the user's history of interaction with the site and do not show any prompts to the user.

Note that research from the Chrome team shows that data is very rarely deleted by the browser. If a user visits a website regularly, there is very little chance that its stored data, even in best-effort mode, will get evicted by the browser.

### Private browsing

Note that in private browsing mode (also called *Incognito* in Chrome, and *InPrivate* in Edge), browsers may apply different quotas, and stored data is usually deleted when the private browsing mode ends.

How much data can be stored?
----------------------------

### Cookies

Different browsers have different rules around how many cookies are allowed per origin and how much space these cookies can use on the disk. While cookies are useful for preserving some small shared state between the browser and the web server across page navigation, using cookies for storing data in the browser is not advised. Cookies are sent with each and every HTTP request, so storing data in cookies that could be stored by using another web technology unnecessarily increases the size of requests.

Because cookies should not be used for storing data in the browser, cookie storage browser limits are not covered here.

### Web Storage

Web Storage, which can be accessed by using the `localStorage` and `sessionStorage` properties of the `window` object, is limited to 10 MiB of data maximum on all browsers.

Browsers can store up to 5 MiB of local storage, and 5 MiB of session storage per origin.

Once this limit is reached, browsers throw a `QuotaExceededError` exception which should be handled by using a `try...catch` block.

### Other web technologies

The data that's stored by using other web technologies, such as IndexedDB, Cache API, or File System API (which defines the Origin Private File System), is managed by a storage management system that's specific to each browser.

This system regulates all of the data that an origin stores using these APIs.

Each browser determines, using whatever mechanism it chooses, the maximum amount of storage a given origin can use.

#### Firefox

In Firefox, the maximum storage space an origin can use in best-effort mode is whichever is the smaller of:

* 10% of the total disk size where the profile of the user is stored.
* Or 10 GiB, which is the *group limit* that Firefox applies to all origins that are part of the same eTLD+1 domain.

Origins for which persistent storage has been granted can store up to 50% of the total disk size, capped at 8 TiB, and are not subject to the eTLD+1 group limit.

For example, if the device has a 500 GiB hard drive, Firefox will allow an origin to store up to:

* In best-effort mode: 10 GiB of data, which is the eTLD+1 group limit.
* In persistent mode: 250 GiB, which is 50% of the total disk size.

Note that it might not actually be possible for the origin to reach its quota because it is calculated based on the hard drive **total** size, not the currently available disk space. This is done for security reasons, to avoid fingerprinting.

#### Chrome and Chromium-based browsers

In browsers based on the Chromium open-source project, including Chrome and Edge, an origin can store up to 60% of the total disk size in both persistent and best-effort modes.

For example, if the device has a 1 TiB hard drive, the browser will allow an origin to use up to 600 GiB.

Like with Firefox, because this quota is calculated based on the hard drive total size to avoid fingerprinting, an origin might not actually be able to reach its quota.

#### Safari

Starting with macOS 14 and iOS 17, Safari allots up to around 20% of the total disk space for each origin. If the user has saved it as a web app on the Home Screen or the Dock, this limit is increased to up to 60% of the disk size. For privacy reasons, cross-origin frames have a separate quota, amounting to roughly 1/10 of their parents.

For instance, a macOS device with a 1 TiB drive will limit each origin to around 200 GiB. If the user stores a web app on its Dock, that will be alloted a greater limit of around 600 GiB.

Like other browsers, the exact limits enforced by the quota may vary as to avoid fingerprinting. Additionally, Safari also enforces an overall quota that stored data across all origins cannot grow beyond: 80% of disk size for each browser and web app, and 15% of disk size for each non-browser app that displays web content. More info on Safari's storage policies can be found on the Webkit blog.

In earlier versions of Safari, an origin is given an initial 1 GiB quota. Once the origin reaches this limit, Safari asks the user for permission to let the origin store more data. This happens whether the origin stores data in best-effort mode or persistent mode.

How to check the available space?
---------------------------------

Web developers can check how much space is available for their origin and how much is being used by the origin with the `navigator.storage.estimate()` method of the Storage API.

Note that this method only returns the estimated usage value, not the actual value. Some of the resources that are stored by an origin may be coming from other origins and browsers voluntarily pad the size of the cross-origin data when reporting total usage value.

What happens when an origin fills its quota?
--------------------------------------------

Attempting to store more than an origin's quota using IndexedDB, Cache, or OPFS, for example, fails with a `QuotaExceededError` exception.

Web developers should wrap JavaScript that writes to browser storage within `try...catch` blocks. Freeing up space by deleting data before storing new data is also recommended.

When is data evicted?
---------------------

Data eviction is the process by which a browser deletes an origin's stored data.

Data eviction can happen in multiple cases:

* When the device is running low on storage space, also known as *storage pressure*.
* When all of the data stored in the browser (across all origins) exceeds the total amount of space the browser is willing to use on the device.
* Proactively, for origins that aren't used regularly, which happens only in Safari.
### Storage pressure eviction

When a device is running low on storage space, also known as *storage pressure*, there may come a point when the browser has less available space than it needs to store all of the origin's stored data.

Browsers use a Least Recently Used (LRU) policy to deal with this scenario. The data from the least recently used origin is deleted. If storage pressure continues, the browser moves on to the second least recently used origin, and so on, until the problem is resolved.

This eviction mechanism only applies to origins that are not persistent and skips over origins that have been granted data persistence by using `navigator.storage.persist()`.

### Browser maximum storage exceeded eviction

Some browsers define a maximum storage space that they can use on the device's hard disk. For example, Chrome currently uses at most 80% of the total disk size.

This maximum storage size means that there may come a point at which the data stored by all of the combined origins exceeds the maximum size without any one origin being above its individual quota.

When this happens, the browser starts evicting best-effort origins as described in Storage pressure eviction.

### Proactive eviction

Safari proactively evicts data when cross-site tracking prevention is turned on. If an origin has no user interaction, such as click or tap, in the last seven days of browser use, its data created from script will be deleted. Cookies set by server are exempt from this eviction.

How is data evicted?
--------------------

When an origin's data is evicted by the browser, all of its data, not parts of it, is deleted at the same time. If the origin had stored data by using IndexedDB and the Cache API for example, then both types of data are deleted.

Only deleting some of the origin's data could cause inconsistency problems.

See also
--------

* Storage for the web on web.dev
* Persistent storage on web.dev
* Chrome Web Storage and Quota Concepts


HTMLElement: hidePopover() method - Web APIs

HTMLElement: hidePopover() 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 **`hidePopover()`** method of the `HTMLElement` interface hides a popover element (i.e. one that has a valid `popover` attribute) by removing it from the top layer and styling it with `display: none`.

When `hidePopover()` is called on a showing element with the `popover` attribute, a `beforetoggle` event will be fired, followed by the popover being hidden, and then the `toggle` event firing. If the element is already hidden, an error is thrown.

Syntax
------

```js
hidePopover()
```

### Parameters

None.

### Return value

None (`undefined`).

### Exceptions

`InvalidStateError` `DOMException`

Thrown if the popover is already hidden.

Examples
--------

The following example provides functionality to hide a popover by pressing a particular key on the keyboard.

### HTML

```html
<button popovertarget="mypopover">Toggle popover's display</button>
<div id="mypopover" popover="manual">
  You can press <kbd>h</kbd> on your keyboard to close the popover.
</div>
```

### JavaScript

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

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

### Result

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

| Specification |
| --- |
| HTML Standard # dom-hidepopover |

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

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

See also
--------

* Popover API


HTMLElement: attachInternals() method - Web APIs

HTMLElement: attachInternals() method
=====================================

 The **`HTMLElement.attachInternals()`** method returns an `ElementInternals` object.
 This method allows a custom element to participate in HTML forms. The `ElementInternals` interface provides utilities for working with these elements in the same way you would work with any standard HTML form element, and also exposes the Accessibility Object Model to the element.

Syntax
------

```js
attachInternals()
```

### Parameters

None.

### Return value

An `ElementInternals` object.

### Exceptions

`NotSupportedError` `DOMException`

Thrown if the element is not a custom element.

`NotSupportedError` `DOMException`

Thrown if the "internals" feature was disabled as part of the element definition.

`NotSupportedError` `DOMException`

Thrown if this method is called twice on the same element.

Examples
--------

The following example demonstrates how to create a custom form-associated element with `HTMLElement.attachInternals`. The `ElementInternals.form` property is then printed to the console to demonstrate that we have an `ElementInternals` object.

```js
class CustomCheckbox extends HTMLElement {
  static formAssociated = true;

  constructor() {
    super();
    this.internals_ = this.attachInternals();
  }
  // …
}

window.customElements.define("custom-checkbox", CustomCheckbox);

let element = document.getElementById("custom-checkbox");
console.log(element.internals_.form);
```

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

| Specification |
| --- |
| HTML Standard # dom-attachinternals |

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

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

See also
--------

* More capable form controls
* Creating custom form controls with ElementInternals


HTMLElement: title property - Web APIs

HTMLElement: title property
===========================

 The **`HTMLElement.title`** property
 represents the title of the element: the text usually displayed in a 'tooltip' popup
 when the mouse is over the node.

Value
-----

A string.

Examples
--------

```js
const link = document.createElement("a");
link.innerText = "grapes";
link.href = "https://en.wikipedia.org/wiki/Grape";
link.title = "Wikipedia page on grapes";
```

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

| Specification |
| --- |
| HTML Standard # dom-title |

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

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

See also
--------

* The HTML **title**
 global attribute.


HTMLElement: mscandidatewindowupdate event - Web APIs

HTMLElement: mscandidatewindowupdate 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 **`mscandidatewindowupdate`** event is thrown after the Input Method Editor (IME) candidate window has been identified as needing to change size, but before any visual updates have rendered.

This proprietary method is specific to Internet Explorer.

An IME candidate window may be identified as needing to change size for any of the following reasons:

* As a result of displaying new / changed alternatives or predictions

Web applications need only register for this event once per element (the handler will remain valid for the lifetime of the element).

Syntax
------

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

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

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

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

A generic `Event` with no added properties.

See also
--------

* Microsoft API extensions
* Related events: `mscandidatewindowshow` and `mscandidatewindowhide`


HTMLElement: spellcheck property - Web APIs

HTMLElement: spellcheck property
================================

The **`spellcheck`** property of the `HTMLElement` interface represents a boolean value that controls the spell-checking hint. It is available on all HTML elements, though it doesn't affect all of them.

It reflects the value of the `spellcheck` HTML global attribute.

Value
-----

A boolean value that is `true` if the spelling and grammar of the text content in the element may be checked, `false` otherwise.

Examples
--------

The following example shows how to control the spell-checking hint via script:

```html
<div>
  <span id="sc-label">The spelling and grammar may be checked: </span>
  <span id="sc-element" contenteditable="true" spellcheck="true">test</span>
</div>
<input id="sc-controller" type="checkbox" checked />Enable spelling and grammar
check
```

```js
const label = document.getElementById("sc-label");
const element = document.getElementById("sc-element");
const controller = document.getElementById("sc-controller");

controller.addEventListener("change", (e) => {
  if (controller.checked) {
    element.spellcheck = true;
    label.innerText = "The spelling and grammar may be checked: ";
  } else {
    element.spellcheck = false;
    label.innerText = "The spelling and grammar may not be checked: ";
  }
});
```

Note that you must enable the browser setting to check spelling and grammar.

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

| Specification |
| --- |
| HTML Standard # dom-spellcheck-dev |

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

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

See also
--------

* `spellcheck` HTML global attribute


HTMLElement: popover property - Web APIs

HTMLElement: popover 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 **`popover`** property of the `HTMLElement` interface gets and sets an element's popover state via JavaScript (`"auto"` or `"manual"`), and can be used for feature detection.

It reflects the value of the `popover` global HTML attribute.

Value
-----

An enumerated value; possible values are:

* `"auto"`: In auto state:
    + The popover can be "light dismissed" — this means that you can hide the popover by clicking outside it or 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 Nested popovers for more details.
* `"manual"`: In manual state:
    + The popover cannot be "light dismissed", although declarative show/hide/toggle buttons will still work.
    + Multiple independent popovers can be shown at a time.
Examples
--------

### Feature detection

You can use the `popover` attribute to feature detect the Popover API:

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

### Setting up a popover programmatically

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

const popoverSupported = supportsPopover();

if (popoverSupported) {
  popover.popover = "auto";
  toggleBtn.popoverTargetElement = popover;
  toggleBtn.popoverTargetAction = "toggle";
} else {
  console.log("Popover API not supported.");
}
```

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

| Specification |
| --- |
| HTML Standard # dom-popover |

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

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

See also
--------

* `popover` HTML global attribute
* Popover API


HTMLElement: draggable property - Web APIs

HTMLElement: draggable property
===============================

The **`draggable`** property of the `HTMLElement` interface gets and sets a `Boolean` primitive indicating if the element is draggable.

It reflects the value of the `draggable` HTML global attribute.

Value
-----

A `Boolean` primitive that is `true` if the element is draggable, `false` otherwise.

Examples
--------

The following example shows how to enable or disable the element's ability to drag via script:

```js
const draggableElement = document.querySelector(".draggable-element");
const notDraggableElement = document.querySelector(".not-draggable-element");

// enable the target element's ability to drag
if (!draggableElement.draggable) {
  draggableElement.draggable = true;
}

// disable the target element's ability to drag
if (notDraggableElement.draggable) {
  notDraggableElement.draggable = false;
}
```

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

| Specification |
| --- |
| HTML Standard # dom-draggable |

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

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

See also
--------

* `draggable` HTML global attribute
* HTML Drag and Drop API overview


HTMLElement: dragleave event - Web APIs

HTMLElement: dragleave event
============================

The `dragleave` event is fired when a dragged element or text selection leaves a valid drop target.

This event is not cancelable and may bubble up to the `Document` and `Window` objects.

Syntax
------

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

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

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

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

A `DragEvent`. Inherits from `Event`.

Event

UIEvent

MouseEvent

DragEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`DragEvent.dataTransfer` Read only

The data that is transferred during a drag-and-drop interaction.

Examples
--------

### Resetting drop zone styles on dragleave

In this example, we have a draggable element inside a container. Try grabbing the element, dragging it over the other container, and releasing it.

We give the other container a purple background while the draggable element is over to signal that it could be dropped onto the container. We listen for the `dragleave` event to reset the container background when dragging the draggable element off the container.

However, in this partial example, we haven't implemented dropping: for a complete example of drag and drop, see the page for the `drag` event.

#### HTML

```html
<div class="dropzone">
  <div id="draggable" draggable="true">This div is draggable</div>
</div>
<div class="dropzone" id="droptarget"></div>
```

#### CSS

```css
body {
  /\* Prevent the user from selecting text in the example \*/
  user-select: none;
}

#draggable {
  text-align: center;
  background: white;
}

.dropzone {
  width: 200px;
  height: 20px;
  background: blueviolet;
  margin: 10px;
  padding: 10px;
}

.dropzone.dragover {
  background-color: purple;
}
```

#### JavaScript

```js
const target = document.getElementById("droptarget");
target.addEventListener("dragenter", (event) => {
  // highlight potential drop target when the draggable element enters it
  if (event.target.classList.contains("dropzone")) {
    event.target.classList.add("dragover");
  }
});

target.addEventListener("dragleave", (event) => {
  // reset background of potential drop target when the draggable element leaves it
  if (event.target.classList.contains("dropzone")) {
    event.target.classList.remove("dragover");
  }
});
```

#### Result

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

| Specification |
| --- |
| HTML Standard # ix-handler-ondragleave |
| HTML Standard # event-dnd-dragleave |

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

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

See also
--------

* Other drag and drop events:
    + `drag`
    + `dragstart`
    + `dragend`
    + `dragover`
    + `dragenter`
    + `drop`