Document: afterscriptexecute event - Web APIs

Document: afterscriptexecute 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 `afterscriptexecute` event fires when a static `<script>` element finishes executing its script. It does not fire if the element is added dynamically, such as with `appendChild()`.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

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

document.addEventListener("afterscriptexecute", finished, true);
// or
document.onafterscriptexecute = finished;
```

View Live Example

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

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

See also
--------

* `Document.beforescriptexecute_event`
* `Document.currentScript`


Document: readyState property - Web APIs

Document: readyState property
=============================

 The **`Document.readyState`** property describes the loading state of the `document`.
 When the value of this property changes, a `readystatechange` event fires on the `document` object.

Value
-----

The `readyState` of a document can be one of following:

`loading`

The `document` is still loading.

`interactive`

 The document has finished loading and the document has been parsed but sub-resources
 such as scripts, images, stylesheets and frames are still loading. The state indicates that
 the `DOMContentLoaded` event is about to fire.

`complete`

 The document and all sub-resources have finished loading. The state indicates that
 the `load` event is about to fire.

Examples
--------

### Different states of readiness

```js
switch (document.readyState) {
  case "loading":
    // The document is loading.
    break;
  case "interactive": {
    // The document has finished loading and we can access DOM elements.
    // Sub-resources such as scripts, images, stylesheets and frames are still loading.
    const span = document.createElement("span");
    span.textContent = "A <span> element.";
    document.body.appendChild(span);
    break;
  }
  case "complete":
    // The page is fully loaded.
    console.log(
      `The first CSS rule is: ${document.styleSheets[0].cssRules[0].cssText}`,
    );
    break;
}
```

### readystatechange as an alternative to DOMContentLoaded event

```js
// Alternative to DOMContentLoaded event
document.onreadystatechange = () => {
  if (document.readyState === "interactive") {
    initApplication();
  }
};
```

### readystatechange as an alternative to load event

```js
// Alternative to load event
document.onreadystatechange = () => {
  if (document.readyState === "complete") {
    initApplication();
  }
};
```

### readystatechange as event listener to insert or modify the DOM before DOMContentLoaded

```js
document.addEventListener("readystatechange", (event) => {
  if (event.target.readyState === "interactive") {
    initLoader();
  } else if (event.target.readyState === "complete") {
    initApp();
  }
});
```

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

| Specification |
| --- |
| HTML Standard # current-document-readiness |

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

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

See also
--------

* Related events:
    + `readystatechange`
    + `DOMContentLoaded`
    + `load`


Document: pointerLockElement property - Web APIs

Document: pointerLockElement property
=====================================

 The **`pointerLockElement`** read-only property of the `Document` interface provides the element set as the target for mouse events while the pointer is locked.
 It is `null` if lock is pending, pointer is unlocked, or the target is in another document.

Value
-----

An `Element` or `null`.

Examples
--------

### Checking pointer lock status

This example contains a `<div>` element that in turn contains a `<button>`. Clicking the button requests pointer lock for the `<div>`.

The example also listens for the `pointerlockchange` event: when this event is fired, the event handler disables the "Lock" button if an element in the document has the pointer lock, and enables the button otherwise.

The effect of this is that if you click the "Lock" button, the pointer is locked and the button is disabled: if you then exit pointer lock (for example, by pressing the `Escape` key), the button is enabled again.

#### HTML

```html
<div id="container">
  <button id="lock">Lock</button>
</div>
```

#### CSS

```css
div {
  height: 100px;
  width: 200px;
  border: 2px solid blue;
}
```

#### JavaScript

```js
const lock = document.querySelector("#lock");
const container = document.querySelector("#container");

lock.addEventListener("click", () => {
  container.requestPointerLock();
});

document.addEventListener("pointerlockchange", () => {
  const locked = document.pointerLockElement;
  lock.disabled = Boolean(locked);
});
```

#### Result

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

| Specification |
| --- |
| Pointer Lock 2.0 # dom-documentorshadowroot-pointerlockelement |

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

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

See also
--------

* `Document.exitPointerLock()`
* `Element.requestPointerLock()`
* Pointer Lock


Document: elementsFromPoint() method - Web APIs

Document: elementsFromPoint() method
====================================

 The **`elementsFromPoint()`** method
 of the `Document` interface returns an array of all elements
 at the specified coordinates (relative to the viewport).
 The elements are ordered from the topmost to the bottommost box of the viewport.

It operates in a similar way to the `elementFromPoint()` method.

Syntax
------

```js
elementsFromPoint(x, y)
```

### Parameters

`x`

The horizontal coordinate of a point.

`y`

The vertical coordinate of a point.

### Return value

An array of `Element` objects, ordered from the topmost to the bottommost box of the viewport.

Examples
--------

### HTML

```html
<div>
  <p>Some text</p>
</div>
<p>Elements at point 30, 20:</p>
<div id="output"></div>
```

### JavaScript

```js
let output = document.getElementById("output");
if (document.elementsFromPoint) {
  let elements = document.elementsFromPoint(30, 20);
  elements.forEach((elt, i) => {
    output.textContent += elt.localName;
    if (i < elements.length - 1) {
      output.textContent += " < ";
    }
  });
} else {
  output.innerHTML =
    '<span style="color: red;">' +
    "Browser does not support <code>document.elementsFromPoint()</code>" +
    "</span>";
}
```

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

| Specification |
| --- |
| CSSOM View Module # dom-document-elementsfrompoint |

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

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

See also
--------

* `Document.elementFromPoint()`


Document: queryCommandState() method - Web APIs

Document: queryCommandState() 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 **`queryCommandState()`** method will tell you if the current selection has a certain `Document.execCommand()` command applied.

Syntax
------

```js
queryCommandState(command)
```

### Parameters

`command` is a command from `Document.execCommand()`

### Return value

`queryCommandState()` can return a boolean value or `null` if the state is unknown.

Example
-------

### HTML

```html
<div contenteditable="true">Select a part of this text!</div>
<button onclick="makeBold();">Test the state of the 'bold' command</button>

<hr />

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

```
hr,
button {
  margin: 1rem 0;
}
```

### JavaScript

```js
function makeBold() {
  const state = document.queryCommandState("bold");
  let message;
  switch (state) {
    case true:
      message = "The bold formatting will be removed from the selected text.";
      break;
    case false:
      message = "The selected text will be displayed in bold.";
      break;
    default:
      message = "The state of the 'bold' command is indeterminable.";
      break;
  }
  document.querySelector("#output").textContent = `Output: ${message}`;
  document.execCommand("bold");
}
```

### Result

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

This feature is not part of any current specification. It is no longer on track to become a standard.

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

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

See also
--------

* `HTMLElement.contentEditable`
* `document.designMode`
* Browser bugs related to `queryCommandState()`: Scribe's "Browser Inconsistencies" documentation


Document: append() method - Web APIs

Document: append() method
=========================

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

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

Syntax
------

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

### Parameters

`param1`, …, `paramN`

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

### Return value

None (`undefined`).

### Exceptions

`HierarchyRequestError` `DOMException`

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

Examples
--------

### Appending a root element to a document

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

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

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

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

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

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

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

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

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

See also
--------

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


Document: prerenderingchange event - Web APIs

Document: prerenderingchange event
==================================

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

The **`prerenderingchange`** event is fired on a prerendered document when it is activated (i.e. the user views the page).

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

The following code sets up an event listener to run a function once prerendering has finished, on a prerendered page (the prerendering is detected via `Document.prerendering`), or runs it immediately on a non-prerendered page:

```js
if (document.prerendering) {
  document.addEventListener("prerenderingchange", initAnalytics, {
    once: true,
  });
} else {
  initAnalytics();
}
```

**Note:** See the Speculation Rules API landing page and particularly the Unsafe speculative loading conditions section for more information on the kinds of activities you might wish to delay until after prerendering has finished.

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

| Specification |
| --- |
| Prerendering Revamped # eventdef-document-prerenderingchange |
| Prerendering Revamped # dom-document-onprerenderingchange |

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

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

See also
--------

* Speculation Rules API
* `prerendering` property


Document: createTreeWalker() method - Web APIs

Document: createTreeWalker() method
===================================

The **`Document.createTreeWalker()`** creator method returns a newly created `TreeWalker` object.

Syntax
------

```js
createTreeWalker(root)
createTreeWalker(root, whatToShow)
createTreeWalker(root, whatToShow, filter)
```

### Parameters

`root`

A `Node` representing the root of the `TreeWalker` object, which is the initial value of `TreeWalker.currentNode`.

`whatToShow` Optional

An `unsigned long` representing a bitmask created by combining the constant properties of `NodeFilter`. It is a convenient way of filtering for certain types of node. It defaults to `0xFFFFFFFF`, representing the `NodeFilter.SHOW_ALL` constant.

| Constant | Numerical value | Description |
| --- | --- | --- |
| `NodeFilter.SHOW_ALL` | `0xFFFFFFFF` | Shows all nodes. |
| `NodeFilter.SHOW_ATTRIBUTE` | `0x2` | Shows `Attr` nodes. |
| `NodeFilter.SHOW_CDATA_SECTION` | `0x8` | Shows `CDATASection` nodes. |
| `NodeFilter.SHOW_COMMENT` | `0x80` | Shows `Comment` nodes. |
| `NodeFilter.SHOW_DOCUMENT` | `0x100` | Shows `Document` nodes. |
| `NodeFilter.SHOW_DOCUMENT_FRAGMENT` | `0x400` | Shows `DocumentFragment` nodes. |
| `NodeFilter.SHOW_DOCUMENT_TYPE` | `0x200` | Shows `DocumentType` nodes. |
| `NodeFilter.SHOW_ELEMENT` | `0x1` | Shows `Element` nodes. |
| `NodeFilter.SHOW_ENTITY`
Deprecated
 | `0x20` | Legacy, no longer effective. |
| `NodeFilter.SHOW_ENTITY_REFERENCE`
Deprecated
 | `0x10` | Legacy, no longer effective. |
| `NodeFilter.SHOW_NOTATION`
Deprecated
 | `0x800` | Legacy, no longer effective. |
| `NodeFilter.SHOW_PROCESSING_INSTRUCTION` | `0x40` | Shows `ProcessingInstruction` nodes. |
| `NodeFilter.SHOW_TEXT` | `0x4` | Shows `Text` nodes. |

**Note:** Since the parent of any `Attr` node is always `null`, `TreeWalker.nextNode()` and `TreeWalker.previousNode()` will never return an `Attr` node. To traverse `Attr` nodes, use `Element.attributes` instead.

`filter` Optional

A callback function or an object with an `acceptNode()` method, which returns `NodeFilter.FILTER_ACCEPT`, `NodeFilter.FILTER_REJECT`, or `NodeFilter.FILTER_SKIP`. The function or method will be called for each node in the subtree based at `root` which is accepted as included by the `whatToShow` flag to determine whether or not to include it in the list of iterable nodes:

* If the return value is `NodeFilter.FILTER_ACCEPT`, this node is included.
* If the return value is `NodeFilter.FILTER_REJECT`, any node in the subtree based at this node is not included.
* If the return value is `NodeFilter.FILTER_SKIP`, this node is not included.

### Return value

A new `TreeWalker` object.

Examples
--------

### Using whatToShow

This example uses `whatToShow` to transform text contents into upper case. Note that the text nodes of the descendants of the `#root` element are also traversed despite of the fact that they are not child nodes of the `#root` element.

#### HTML

```html
<div id="root">
  This is a text node.
  <span>And this is a <code>span</code> element.</span>
</div>
```

#### CSS

```css
span {
  background-color: aqua;
}
```

#### JavaScript

```js
const treeWalker = document.createTreeWalker(
  document.querySelector("#root"),
  NodeFilter.SHOW\_TEXT,
);

while (treeWalker.nextNode()) {
  const node = treeWalker.currentNode;
  node.data = node.data.toUpperCase();
}
```

#### Result

### Using filter

This example uses `filter` to escape text contents. For any text node, its content will be escaped using `encodeURI()` if it is a descendant of an `.escape` element but not of any `.no-escape` element.

#### HTML

```html
<div>
  <div>
    This is not escaped. <span class="escape">But this is escaped.</span>
  </div>
  <div class="escape">This is escaped.</div>
  <div class="no-escape">This is not escaped.</div>
</div>
<hr />
<div class="escape">
  <div>
    This is escaped. <span class="no-escape">But this is not escaped.</span>
  </div>
  <div class="no-escape">This is not escaped.</div>
</div>
<hr />
<div class="no-escape">
  <div>This is not escaped.</div>
  <div class="escape">This is not escaped.</div>
</div>
```

#### CSS
```

div {
  margin: 0.25em 0;
  padding: 0.25em;
}
span {
  display: inline-block;
}
```

```css
.escape {
  border: dashed;
}
.no-escape {
  border: solid;
}
```

#### JavaScript

```js
const treeWalker = document.createTreeWalker(
  document.body,
  NodeFilter.SHOW\_ELEMENT,
  (node) =>
    node.classList.contains("no-escape")
      ? NodeFilter.FILTER\_REJECT
      : node.closest(".escape")
        ? NodeFilter.FILTER\_ACCEPT
        : NodeFilter.FILTER\_SKIP,
);

while (treeWalker.nextNode()) {
  for (const node of treeWalker.currentNode.childNodes) {
    if (node.nodeType === Node.TEXT\_NODE && /\S/.test(node.data)) {
      // Exclude whitespace-only text nodes
      node.data = encodeURI(node.data.replace(/\s+/g, " "));
    }
  }
}
```

#### Result

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

| Specification |
| --- |
| DOM Standard # dom-document-createtreewalker |

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

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

See also
--------

* `TreeWalker`: Related interface


Document: applets property - Web APIs

Document: applets property
==========================

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

The **`applets`** property of the `Document` returns an empty `HTMLCollection`. This property is kept only for compatibility reasons; in older versions of browsers, it returned a list of the applets within a document.

**Note:** Support for the `<applet>` element has been removed by all browsers. Therefore, calling `document.applets` always
 returns an empty collection.

Value
-----

An empty `HTMLCollection`.

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

| Specification |
| --- |
| HTML Standard # dom-document-applets |

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

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


Document: getElementsByName() method - Web APIs

Document: getElementsByName() method
====================================

 The **`getElementsByName()`** method
 of the `Document` object returns a `NodeList` Collection of
 elements with a given `name` attribute in the document.

Syntax
------

```js
getElementsByName(name)
```

### Parameters

`name`

The value of the `name` attribute of the element(s) we are looking for.

### Return value

A live `NodeList` collection, meaning it automatically updates as new elements with the same `name` are added to, or removed from, the document.

Examples
--------

```html
<!doctype html>
<html lang="en">
  <head>
    <title>Example: using document.getElementsByName</title>
  </head>
  <body>
    <input type="hidden" name="up" />
    <input type="hidden" name="down" />
  </body>
</html>
```

```js
const up_names = document.getElementsByName("up");
console.log(up_names[0].tagName); // displays "INPUT"
```

Notes
-----

 The `name` attribute can only be applied in (X)HTML
 documents.

 The returned `NodeList` Collection contains *all* elements with the
 given `name`, such as `<meta>`, `<object>`, and
 even elements which do not support the `name` attribute at all.

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

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

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

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

See also
--------

* `document.getElementById()` to return a reference to an element by its
 unique `id`
* `document.getElementsByTagName()` to return references to elements with
 the same tag name
* `document.querySelector()` to return references to elements via CSS
 selectors like `'div.myclass'`


Document: paste event - Web APIs

Document: paste event
=====================

The **`paste`** event fires when the user initiates a paste action through the browser's user interface.

The original target for this event is the `Element` that was the intended target of the paste action. You can listen for this event on the `Document` interface to handle it in the capture or bubbling phases. For full details on this event please see the page on the Element: paste event.

Syntax
------

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

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

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

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

A `ClipboardEvent`. Inherits from `Event`.

Event

ClipboardEventExamples
--------

To be informed when a user pastes data to the webpage from their clipboard, you can add a handler to your `Document` instance using `addEventListener()`, like this:

```js
document.addEventListener("paste", (event) => {
  /\* the session has shut down \*/
});
```

Alternatively, you can use the `Document.onpaste` event handler property to establish a handler for the `paste` event:

```js
document.onpaste = (event) => {
  /\* the session has shut down \*/
};
```

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

| Specification |
| --- |
| Clipboard API and events # clipboard-event-paste |
| HTML Standard # handler-onpaste |

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

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

See also
--------

* Related events: `copy`, `cut`
* This event on `Element` targets: `paste`
* This event on `Window` targets: `paste`


Document: images property - Web APIs

Document: images property
=========================

 The **`images`** read-only property of
 the `Document` interface returns a collection of the images in the current HTML document.

Value
-----

 An `HTMLCollection` providing a live list of all of the images contained
 in the current document. Each entry in the collection is an
 `HTMLImageElement` representing a single image element.

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

 You can use either JavaScript array notation or the `item()` method on the returned collection to access the items in the collection. The
 following are equivalent:

```js
firstImage = imageCollection.item(0);

firstImage = imageCollection[0];
```

Examples
--------

 This example looks through the list of images and finds one whose name is
 `"banner.gif"`.

```js
for (const image of document.images) {
  if (image.src === "banner.gif") {
    console.log("Found the banner");
  }
}
```

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

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

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

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


Document: getElementById() method - Web APIs

Document: getElementById() method
=================================

The **`getElementById()`** method of the `Document` interface returns an `Element` object representing the element whose `id` property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.

If you need to get access to an element which doesn't have an ID, you can use `querySelector()` to find the element using any selector.

**Note:** IDs should be unique inside a document. If two or more elements in a document have the same ID, this method returns the first element found.

Syntax
------

```js
getElementById(id)
```

**Note:** The capitalization of `"Id"` in the name of this method *must* be correct for the code to function; `getElementByID()` is *not* valid and will not work, however natural it may seem.

### Parameters

`id`

The ID of the element to locate. The ID is a case-sensitive string which is unique within the document; only one element should have any given ID.

### Return value

An `Element` object describing the DOM element object matching the specified ID, or `null` if no matching element was found in the document.

Examples
--------

### HTML

```html
<html lang="en">
  <head>
    <title>getElementById example</title>
  </head>
  <body>
    <p id="para">Some text here</p>
    <button onclick="changeColor('blue');">blue</button>
    <button onclick="changeColor('red');">red</button>
  </body>
</html>
```

### JavaScript

```js
function changeColor(newColor) {
  const elem = document.getElementById("para");
  elem.style.color = newColor;
}
```

### Result

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

Unlike some other element-lookup methods such as `Document.querySelector()` and `Document.querySelectorAll()`, `getElementById()` is only available as a method of the global `document` object, and *not* available as a method on all element objects in the DOM. Because ID values must be unique throughout the entire document, there is no need for "local" versions of the function.

### Example

```html
<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>
  <body>
    <div id="parent-id">
      <p>hello word1</p>
      <p id="test1">hello word2</p>
      <p>hello word3</p>
      <p>hello word4</p>
    </div>
    <script>
 const parentDOM = document.getElementById("parent-id");
 const test1 = parentDOM.getElementById("test1");
 // throw error
 // Uncaught TypeError: parentDOM.getElementById is not a function
 </script>
  </body>
</html>
```

If there is no element with the given `id`, this function returns `null`. Note that the `id` parameter is case-sensitive, so `document.getElementById("Main")` will return `null` instead of the element `<div id="main">` because "M" and "m" are different for the purposes of this method.

Elements not in the document are not searched by `getElementById()`. When creating an element and assigning it an ID, you have to insert the element into the document tree with `Node.insertBefore()` or a similar method before you can access it with `getElementById()`:

```js
const element = document.createElement("div");
element.id = "testqq";
const el = document.getElementById("testqq"); // el will be null!
```

In non-HTML documents, the DOM implementation must have information on which attributes are of type ID. Attributes with the name "id" are not of type ID unless so defined in the document's DTD. The `id` attribute is defined to be of ID type in the common cases of XHTML, XUL, and others. Implementations that do not know whether attributes are of type ID or not are expected to return `null`.

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-nonelementparentnode-getelementbyid② |

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

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

See also
--------

* `Document` reference for other methods and properties you can use to get references to elements in the document.
* `Document.querySelector()` for selectors via queries like `'div.myclass'`
* xml:id - has a utility method for allowing `getElementById()` to obtain 'xml:id' in XML documents


Document: alinkColor property - Web APIs

Document: alinkColor property
=============================

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

 Returns or sets the color of an active link in the document body. A link is active
 during the time between `mousedown` and `mouseup` events.

Value
-----

A string containing the name of the color (e.g., `blue`, `darkblue`, etc.) or the hexadecimal value of the color (e.g., `#0000FF`).

Notes
-----

 The default value for this property in Mozilla Firefox is red (`#ee0000` in
 hexadecimal).

`document.alinkColor` is deprecated in DOM Level 2 HTML. One alternative is the CSS selector `:active`.

Another alternative is `document.body.aLink`, although this is deprecated in HTML 4.01 in favor of the CSS alternative.

 Firefox supports both `alinkColor`/`:active` and `:focus`. Internet
 Explorer 6 and 7 support `alinkColor`/`:active` only for HTML anchor (<a>) links and the
 behavior is the same as `:focus` under Gecko. There is no support for
 `:focus` in IE.

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

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


Document: fullscreenElement property - Web APIs

Document: fullscreenElement property
====================================

 The
 **`Document.fullscreenElement`** read-only
 property returns the `Element` that is currently being presented in
 fullscreen mode in this document, or `null` if fullscreen mode is not
 currently in use.

 Although this property is read-only, it will not throw if it is modified (even in
 strict mode); the setter is a no-operation and it will be ignored.

Value
-----

 The `Element` object that's currently in fullscreen mode; if fullscreen
 mode isn't currently in use by the `document`, the returned
 value is `null`.

Examples
--------

 This example presents a function, `isVideoInFullscreen()`, which looks at
 the value returned by `fullscreenElement`; if the document is in fullscreen
 mode (`fullscreenElement` isn't `null`) and the fullscreen
 element's `nodeName` is `VIDEO`, indicating a
 `<video>` element, the function returns `true`, indicating
 that the video is in fullscreen mode.

```js
function isVideoInFullscreen() {
  if (document.fullscreenElement?.nodeName === "VIDEO") {
    return true;
  }
  return false;
}
```

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

| Specification |
| --- |
| Fullscreen API Standard # ref-for-dom-document-fullscreenelement① |

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

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

See also
--------

* Fullscreen API
* Guide to the Fullscreen API
* `Element.requestFullscreen()`
* `Document.exitFullscreen()`
* `:fullscreen` and `::backdrop`
* The `<iframe>` `allowfullscreen`
 attribute


Document: fonts property - Web APIs

Document: fonts property
========================

The **`fonts`** property of the `Document` interface returns the `FontFaceSet` interface of the document.

This feature is part of the CSS Font Loading API.

Value
-----

 The returned value is the `FontFaceSet` interface of the document.
 The `FontFaceSet` interface is useful for loading new fonts, checking the status of previously loaded fonts etc.

Examples
--------

### Doing operation after fonts are loaded

```js
document.fonts.ready.then((fontFaceSet) => {
  // Any operation that needs to be done only after all used fonts
  // have finished loading can go here.
  const fontFaces = [...fontFaceSet];
  console.log(fontFaces);
  // some fonts may still be unloaded if they aren't used on the site
  console.log(fontFaces.map((f) => f.status));
});
```

The promise fulfils when loading and layout operations of all used fonts are done. The set of used fonts can be different from the set of *declared* fonts, e.g. if optional fonts (i.e. fonts declared via `font-display: optional`) were not able to load in time.

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

| Specification |
| --- |
| CSS Font Loading Module Level 3 # FontFaceSet-interface |

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

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

See also
--------

* `FontFaceSet` interface
* `FontFace`


Document: xmlEncoding property - Web APIs

Document: xmlEncoding property
==============================

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

Returns the encoding as determined by the XML declaration. Should be `null` if unspecified or unknown.

**Warning:** Do not use this attribute; it has been removed from the DOM Level 4 specification and is no longer supported in Firefox 10.0.

Consider the following XML Declaration:

```xml
<?xml version="1.0" encoding="UTF-16"?>
```

Then, the result should be "UTF-16".

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

This feature is not part of any specification anymore. It is no more on track to become a standard.

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

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


Document: styleSheetSets property - Web APIs

Document: styleSheetSets property
=================================

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

**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 **`styleSheetSets`** read-only property returns a live list of all of the currently-available style sheet sets.

Value
-----

A list of style sheet sets that are available.

Examples
--------

 Given an `<ul>` (list) element with the ID "sheetList", you can populate
 it with the names of all the available style sheet sets with code like this:

```js
const list = document.getElementById("sheetList");
const sheets = document.styleSheetSets;

list.textContent = "";

for (const sheet of sheets) {
  const item = document.createElement("li");
  item.textContent = sheet;
  list.appendChild(item);
}
```

Notes
-----

 The list of available style sheet sets is constructed by enumerating all the style
 sheets available for the document, in the order in which they're listed in the
 `Document.styleSheets` attribute, adding the `title` of each
 style sheet that has a title to the list. Duplicates are dropped from the list (using a
 case-sensitive comparison).

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

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

See also
--------

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


Document: caretPositionFromPoint() method - Web APIs

Document: caretPositionFromPoint() method
=========================================

 The **`caretPositionFromPoint()`**
 method of the `Document` interface returns a
 `CaretPosition` object, containing the DOM node, along with the caret and
 caret's character offset within that node.

Syntax
------

```js
caretPositionFromPoint(x, y)
```

### Parameters

`x`

The horizontal coordinate of a point.

`y`

The vertical coordinate of a point.

### Return value

A `CaretPosition` object.

Examples
--------

Click anywhere in the **Demo** paragraph below to insert a line break at the point where you click. The code for it is below the demo.

### Demo

The code below first checks for `document.caretPositionFromPoint` support, but if the browser doesn't support that, the code then checks for `document.caretRangeFromPoint`, and uses that instead.

### JavaScript

```js
function insertBreakAtPoint(e) {
  let range;
  let textNode;
  let offset;

  if (document.caretPositionFromPoint) {
    range = document.caretPositionFromPoint(e.clientX, e.clientY);
    textNode = range.offsetNode;
    offset = range.offset;
  } else if (document.caretRangeFromPoint) {
    // Use WebKit-proprietary fallback method
    range = document.caretRangeFromPoint(e.clientX, e.clientY);
    textNode = range.startContainer;
    offset = range.startOffset;
  } else {
    // Neither method is supported, do nothing
    return;
  }
  // Only split TEXT\_NODEs
  if (textNode?.nodeType === 3) {
    let replacement = textNode.splitText(offset);
    let br = document.createElement("br");
    textNode.parentNode.insertBefore(br, replacement);
  }
}

let paragraphs = document.getElementsByTagName("p");
for (const paragraph of paragraphs) {
  paragraph.addEventListener("click", insertBreakAtPoint, false);
}
```

```
let message = document.getElementById("message");
if (document.caretPositionFromPoint) {
  message.textContent =
    "This browser supports the standard document.caretPositionFromPoint";
  message.classList.add("supported");
} else if (document.caretRangeFromPoint) {
  message.textContent =
    "This browser supports the non-standard document.caretRangeFromPoint";
  message.classList.add("supported");
}
```

### HTML
```

<div id="message">
  This browser supports neither document.caretRangeFromPoint nor
  document.caretPositionFromPoint
</div>
```

```html
<p>
  Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy
  eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam
  voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita
  kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
</p>
```

```
#message {
  color: red;
  font-weight: bold;
}

#message.fallback {
  color: darkorange;
}

#message.supported {
  color: green;
}
```

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

| Specification |
| --- |
| CSSOM View Module # dom-document-caretpositionfrompoint |

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

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

See also
--------

* `CaretPosition`


Document: adoptedStyleSheets property - Web APIs

Document: adoptedStyleSheets property
=====================================

The **`adoptedStyleSheets`** property of the `Document` interface is used for setting an array of constructed stylesheets to be used by the document.

**Note:** A constructed stylesheet is a stylesheet created programmatically using the `CSSStyleSheet()` constructor (as compared to one created by a user-agent when importing a stylesheet from a script, imported using `<style>` and `@import`, or linked to via `<link>`).

 The same constructed stylesheets can also be shared with one or more `ShadowRoot` instances using the `ShadowRoot.adoptedStyleSheets` property.
 Changing an adopted stylesheet will affect all the objects that adopt it.

 Stylesheets in the property are evaluated along with the document's other stylesheets using the CSS cascade algorithm.
 Where the resolution of rules considers stylesheet order, `adoptedStyleSheets` are assumed to be ordered after those in `Document.styleSheets`.

Only stylesheets created using the `CSSStyleSheet()` constructor within the context of the current `Document` may be adopted.

Value
-----

The value is an array of `CSSStyleSheet` instances that must have been created using the `CSSStyleSheet()` constructor within the context of the same `Document`.

If the array needs to be modified, use in-place mutations like `push()`. The `CSSStyleSheet` instances themselves can also be modified, and these changes will apply wherever the stylesheet is adopted.

In an earlier version of the specification, the array was not modifiable, so the only way to add new stylesheets was to assign a new array to `adoptedStyleSheets`.

### Exceptions

`NotAllowedError` `DOMException`

One of the `CSSStyleSheet` instances in the array was not created using the `CSSStyleSheet()` constructor or was constructed in a different document than the current document, such as one in a frame.

Examples
--------

### Adopting a stylesheet

 The code below shows a stylesheet being constructed, and then `CSSStyleSheet.replaceSync()` is called to add a rule to the sheet.
 The stylesheet is then added to an array and assigned to the `adoptedStyleSheets` property.

```js
// Create an empty "constructed" stylesheet
const sheet = new CSSStyleSheet();
// Apply a rule to the sheet
sheet.replaceSync("a { color: red; }");

// Apply the stylesheet to a document
document.adoptedStyleSheets = [sheet];
```

We can append a new rule to the stylesheet using `CSSStyleSheet.insertRule()`.

```js
sheet.insertRule("\* { background-color: blue; }");
// The document will now have blue background.
```

### Append a new stylesheet

 To append a whole new stylesheet to the `adoptedStyleSheets` property we have to create and assign a new combined array.
 This is demonstrated below using spread-syntax:

```js
const extraSheet = new CSSStyleSheet();
extraSheet.replaceSync("p { color: green; }");

// Combine the existing sheets and new one
document.adoptedStyleSheets = [...document.adoptedStyleSheets, extraSheet];
```

Sharing a stylesheet with a shadow DOM
--------------------------------------

We can share a stylesheet to a shadow root in a similar way.

```js
// Create an element in the document and then create a shadow root:
const node = document.createElement("div");
const shadow = node.attachShadow({ mode: "open" });

//Adopt the same sheet into the shadow DOM
shadow.adoptedStyleSheets = [sheet];
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-documentorshadowroot-adoptedstylesheets |

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

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

See also
--------

* Constructable Stylesheets (web.dev)
* Using the Shadow DOM
* `CSSStyleSheet()` constructor
* `CSSStyleSheet.replaceSync()`
* `CSSStyleSheet.replace()`
* `CSSStyleSheet.insertRule()`
* `CSSStyleSheet.deleteRule()`


Document: copy event - Web APIs

Document: copy event
====================

The **`copy`** event fires when the user initiates a copy action through the browser's user interface.

The original target for this event is the `Element` that was the intended target of the copy action. You can listen for this event on the `Document` interface to handle it in the capture or bubbling phases. For full details on this event please see the page on the Element: copy event.

Syntax
------

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

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

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

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

A `ClipboardEvent`. Inherits from `Event`.

Event

ClipboardEventExamples
--------

To be informed when a user copies data from the webpage to their clipboard, you can add a handler to your `Document` instance using `addEventListener()`, like this:

```js
document.addEventListener("copy", (event) => {
  /\* the session has shut down \*/
});
```

Alternatively, you can use the `Document.oncopy` event handler property to establish a handler for the `copy` event:

```js
document.oncopy = (event) => {
  /\* the session has shut down \*/
};
```

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

| Specification |
| --- |
| Clipboard API and events # clipboard-event-copy |
| HTML Standard # handler-oncopy |

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

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

See also
--------

* Related events: `cut`, `paste`
* This event on `Element` targets: `copy`
* This event on `Window` targets: `copy`


Document: bgColor property - Web APIs

Document: bgColor property
==========================

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

 The deprecated `bgColor` property gets or sets the background color of the
 current document.

Value
-----

A string representing the color as a word (e.g., "red") or hexadecimal value (e.g., "`#ff0000`").

Examples
--------

```js
document.bgColor = "darkblue";
```

Notes
-----

 The default value for this property in Firefox is white (`#ffffff` in
 hexadecimal).

`document.bgColor` is deprecated in DOM Level 2 HTML. The recommended alternative is use of the CSS style
 `background-color` which can be accessed through the DOM with
 `document.body.style.backgroundColor`. Another alternative is
 `document.body.bgColor`, although this is also deprecated in HTML 4.01 in
 favor of the CSS alternative.

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

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


Document: exitPointerLock() method - Web APIs

Document: exitPointerLock() method
==================================

The **`exitPointerLock()`** method of the `Document` interface asynchronously releases a pointer lock previously requested through `Element.requestPointerLock`.

**Note:** While the **`exitPointerLock()`** method is called on the document, the **`requestPointerLock()`** method is called on an element.

To track the success or failure of the request, it is necessary to listen for the `pointerlockchange` and `pointerlockerror` events.

Syntax
------

```js
exitPointerLock()
```

### Parameters

None.

### Return value

None (`undefined`).

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

| Specification |
| --- |
| Pointer Lock 2.0 # dom-document-exitpointerlock |

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

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

See also
--------

* `Document.pointerLockElement`
* `Element.requestPointerLock()`
* Pointer Lock


Document: createProcessingInstruction() method - Web APIs

Document: createProcessingInstruction() method
==============================================

`createProcessingInstruction()` generates a new processing instruction node and returns it.

The new node usually will be inserted into an XML document in order to accomplish anything with it, such as with `node.insertBefore`.

Syntax
------

```js
createProcessingInstruction(target, data)
```

### Parameters

* `piNode` is the resulting `ProcessingInstruction` node.
* `target` is a string containing the first part of the processing instruction (i.e., `<?target … ?>`)
* `data` is a string containing any information the processing instruction should carry, after the target. The data is up to you, but it can't contain `?>`, since that closes the processing instruction.
### Return value

None (`undefined`).

### Exceptions

`InvalidCharacterError` `DOMException`

Thrown if either of the following are true:

* The `target` value is not a valid XML name; for example, it starts with a number, hyphen, or period, or contains characters other than alphanumeric characters, underscores, hyphens, or periods.
* The *closing processing instruction sequence* (`?>`) is part of the `data` value.

Examples
--------

```js
const doc = new DOMParser().parseFromString("<foo />", "application/xml");
const pi = doc.createProcessingInstruction(
  "xml-stylesheet",
  'href="mycss.css"',
);

doc.insertBefore(pi, doc.firstChild);

console.log(new XMLSerializer().serializeToString(doc));
// Displays: <?xml-stylesheet href="mycss.css" type="text/css"?><foo/>
```

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

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

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

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


Document: caretRangeFromPoint() method - Web APIs

Document: caretRangeFromPoint() method
======================================

**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 **`caretRangeFromPoint()`** method of the
 `Document` interface returns a `Range` object for the document
 fragment under the specified coordinates.

This method is the WebKit-proprietary implementation of the `Document.caretPositionFromPoint` method.

Syntax
------

```js
caretRangeFromPoint(x, y)
```

### Parameters

`x`

A horizontal position within the current viewport.

`y`

A vertical position within the current viewport.

### Return value

One of the following:

* A `Range`.
* `Null`, if *x* or *y* are negative, outside viewport,
 or there is no text entry node.
Examples
--------

Visit the `Document.caretPositionFromPoint` page to view a live sample of this method.

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

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


Document: exitFullscreen() method - Web APIs

Document: exitFullscreen() method
=================================

 The `Document` method
 **`exitFullscreen()`** requests that the element on this
 document which is currently being presented in fullscreen mode be taken out of
 fullscreen mode, restoring the previous state of the screen. This usually
 reverses the effects of a previous call to `Element.requestFullscreen()`.

Syntax
------

```js
exitFullscreen()
```

### Parameters

None.

### Return value

 A `Promise` which is resolved once the user agent has
 finished exiting fullscreen mode. If an error occurs while attempting to exit
 fullscreen mode, the `catch()` handler for the promise is called.

Examples
--------

 This example causes the current document to toggle in and out of a fullscreen
 presentation whenever the mouse button is clicked within it.

```js
document.onclick = (event) => {
  if (document.fullscreenElement) {
    document
      .exitFullscreen()
      .then(() => console.log("Document Exited from Full screen mode"))
      .catch((err) => console.error(err));
  } else {
    document.documentElement.requestFullscreen();
  }
};
```

**Note:** For a more complete example, see the
 `Element.requestFullscreen()` examples.

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

| Specification |
| --- |
| Fullscreen API Standard # ref-for-dom-document-exitfullscreen① |

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

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

See also
--------

* Fullscreen API
* Guide to the Fullscreen API
* `Element.requestFullscreen()`
* `Document.fullscreenElement`
* `:fullscreen` and `::backdrop`
* The `<iframe>` `allowfullscreen`
 attribute


Document: clear() method - Web APIs

Document: clear() 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.

The **`Document.clear()`** method does nothing, but doesn't raise any error.

Syntax
------

```js
clear()
```

### Parameters

None.

### Return value

None (`undefined`).

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

| Specification |
| --- |
| HTML Standard # dom-document-clear |

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

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


Document: visibilitychange event - Web APIs

Document: visibilitychange event
================================

The `visibilitychange` event is fired at the document when the contents of its tab have become visible or have been hidden.

The event is not cancelable.

Syntax
------

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

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

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

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

A generic `Event`.

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

The event doesn't include the document's updated visibility status, but you can get that information from the document's `visibilityState` property.

This event fires with a `visibilityState` of `hidden` when a user navigates to a new page, switches tabs, closes the tab, minimizes or closes the browser, or, on mobile, switches from the browser to a different app. Transitioning to `hidden` is the last event that's reliably observable by the page, so developers should treat it as the likely end of the user's session (for example, for sending analytics data).

The transition to `hidden` is also a good point at which pages can stop making UI updates and stop any tasks that the user doesn't want to have running in the background.

Examples
--------

### Pausing music on transitioning to hidden

This example begins playing a music track when the document becomes visible, and pauses the music when the document is no longer visible.

```js
document.addEventListener("visibilitychange", () => {
  if (document.visibilityState === "visible") {
    backgroundMusic.play();
  } else {
    backgroundMusic.pause();
  }
});
```

### Sending end-of-session analytics on transitioning to hidden

 This example treats the transition to `hidden` as the end of the user's session, and sends the appropriate analytics using the `Navigator.sendBeacon()`
 API:

```js
document.onvisibilitychange = () => {
  if (document.visibilityState === "hidden") {
    navigator.sendBeacon("/log", analyticsData);
  }
};
```

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

| Specification |
| --- |
| HTML Standard # event-visibilitychange |
| HTML Standard # handler-onvisibilitychange |

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

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

See also
--------

* Page Visibility API
* `Document.visibilityState`
* Don't lose user and app state, use Page Visibility explains in detail why you should use `visibilitychange`, not `beforeunload`/`unload`.
* Page Lifecycle API gives best-practices guidance on handling page lifecycle behavior in your web applications.


Document: getSelection() method - Web APIs

Document: getSelection() method
===============================

 The **`getSelection()`** method of
 the `Document` interface returns a `Selection`
 object representing the range of text selected by the user, or the current position of
 the caret.

Syntax
------

```js
getSelection()
```

### Parameters

None.

### Return value

A `Selection` object.

Examples
--------

### Getting a Selection object

```js
let selection = document.getSelection();
let selRange = selection.getRangeAt(0);
// do stuff with the range

console.log(selection); // Selection object
```

### String representation of the Selection object

 Some functions (like `Window.alert()`) call `toString()`
 automatically and the returned value is passed to the function. As a consequence, this will return the selected text
 and not the `Selection` object:

```js
alert(selection);
```

 However, not all functions call `toString()` automatically.
 To use a `Selection` object as a string, call its `toString()` method directly:

```js
let selectedText = selection.toString();
```

Related objects
---------------

 You can call `Window.getSelection()`, which works identically to
 `Document.getSelection()`.

 It is worth noting that currently `getSelection()` doesn't work on the
 content of `<input>` elements in Firefox.
 `HTMLInputElement.setSelectionRange()`) could be used to work around this.

 Notice also the difference between *selection* and *focus*.
 `Document.activeElement` returns the focused element.

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

| Specification |
| --- |
| Selection API # dom-document-getselection |

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

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


Document: compatMode property - Web APIs

Document: compatMode property
=============================

 The **`Document.compatMode`** read-only property indicates
 whether the document is rendered in Quirks mode or
 Standards mode.

Value
-----

An enumerated value that can be:

* "`BackCompat`" if the document is in quirks mode.
* "`CSS1Compat`" if the document is in no-quirks (also known as
 "standards") mode or limited-quirks (also known as "almost standards") mode.

**Note:** All these modes are now standardized, so the older "standards"
 and "almost standards" names are nonsensical and no longer used in standards.

Examples
--------

```js
if (document.compatMode === "BackCompat") {
  // in Quirks mode
}
```

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

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

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

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


Document: DOMContentLoaded event - Web APIs

Document: DOMContentLoaded event
================================

The **`DOMContentLoaded`** event fires when the HTML document has been completely parsed, and all deferred scripts (`<script defer src="…">` and `<script type="module">`) have downloaded and executed. It doesn't wait for other things like images, subframes, and async scripts to finish loading.

`DOMContentLoaded` does not wait for stylesheets to load, however deferred scripts *do* wait for stylesheets, and the `DOMContentLoaded` event is queued after deferred scripts. Also, scripts which aren't deferred or async (e.g. `<script>`) will wait for already-parsed stylesheets to load.

A different event, `load`, should be used only to detect a fully-loaded page. It is a common mistake to use `load` where `DOMContentLoaded` would be more appropriate.

This event is not cancelable.

Syntax
------

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

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

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

A generic `Event`.

Examples
--------

### Basic usage

```js
document.addEventListener("DOMContentLoaded", (event) => {
  console.log("DOM fully loaded and parsed");
});
```

### Delaying DOMContentLoaded

```html
<script>
 document.addEventListener("DOMContentLoaded", (event) => {
 console.log("DOM fully loaded and parsed");
 });

 for (let i = 0; i < 1\_000\_000\_000; i++);
 // This synchronous script is going to delay parsing of the DOM,
 // so the DOMContentLoaded event is going to launch later.
</script>
```

### Checking whether loading is already complete

`DOMContentLoaded` may fire before your script has a chance to run, so it is wise to check before adding a listener.

```js
function doSomething() {
  console.info("DOM loaded");
}

if (document.readyState === "loading") {
  // Loading hasn't finished yet
  document.addEventListener("DOMContentLoaded", doSomething);
} else {
  // `DOMContentLoaded` has already fired
  doSomething();
}
```

**Note:** There's no race condition here — it's not possible for the document to be loaded between the `if` check and the `addEventListener()` call. JavaScript has run-to-completion semantics, which means if the document is loading at one particular tick of the event loop, it can't become loaded until the next cycle, at which time the `doSomething` handler is already attached and will be fired.

### Live example

#### HTML

```html
<div class="controls">
  <button id="reload" type="button">Reload</button>
</div>

<div class="event-log">
  <label for="eventLog">Event log:</label>
  <textarea
 readonly
 class="event-log-contents"
 rows="8"
 cols="30"
 id="eventLog"></textarea>
</div>
```

```
body {
  display: grid;
  grid-template-areas: "control log";
}

.controls {
  grid-area: control;
  display: flex;
  align-items: center;
  justify-content: center;
}

.event-log {
  grid-area: log;
}

.event-log-contents {
  resize: none;
}

label,
button {
  display: block;
}

#reload {
  height: 2rem;
}
```

#### JavaScript

```js
const log = document.querySelector(".event-log-contents");
const reload = document.querySelector("#reload");

reload.addEventListener("click", () => {
  log.textContent = "";
  setTimeout(() => {
    window.location.reload(true);
  }, 200);
});

window.addEventListener("load", (event) => {
  log.textContent += "load\n";
});

document.addEventListener("readystatechange", (event) => {
  log.textContent += `readystate: ${document.readyState}\n`;
});

document.addEventListener("DOMContentLoaded", (event) => {
  log.textContent += "DOMContentLoaded\n";
});
```

#### Result

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

| Specification |
| --- |
| HTML Standard # stop-parsing |

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

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

See also
--------

* Related events: `load`, `readystatechange`, `beforeunload`, `unload`


Document: createTouchList() method - Web APIs

Document: createTouchList() 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 **`Document.createTouchList()`** method creates and returns a new `TouchList` object.

Syntax
------

```js
createTouchList(touch1)
createTouchList(touch1, touch2)
createTouchList(touch1, touch2, /\* …, \*/ touchN)
```

### Parameters

`touch1`, …, `touchN`

 Zero or more `Touch` objects. **Note:** Firefox also
 accepts an array of
 `Touch` objects.

### Return value

`list`

 A `TouchList` object containing the `Touch` objects
 specified by the `touches` parameter.

Examples
--------

 This example illustrates using the `Document.createTouchList()` method to
 create `TouchList` objects.

 In following code snippet, some `Touch` objects are created for the
 `target` element and those touch points are then used to create some
 `TouchList` objects.

```js
const target = document.getElementById("target");

// Create some touch points
const touch1 = document.createTouch(window, target, 1, 15, 20, 35, 40);
const touch2 = document.createTouch(window, target, 2, 25, 30, 45, 50);

// Create an empty TouchList objects
const list0 = document.createTouchList();

// Create a TouchList with only one Touch object
const list1 = document.createTouchList(touch1);

// Create a list with two Touch objects
const list2 = document.createTouchList(touch1, touch2);
```

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

This feature is not part of any current specification. It is no longer on track to become a standard.

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

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

See also
--------

* Touch events
* `Touch`
* `TouchEvent`
* `TouchList`
* `Document.createTouch()`


Document: implementation property - Web APIs

Document: implementation property
=================================

 The **`Document.implementation`** property returns a
 `DOMImplementation` object associated with the current document.

Value
-----

A `DOMImplementation` object.

Examples
--------

```js
const modName = "HTML";
const modVer = "2.0";
const conformTest = document.implementation.hasFeature(modName, modVer);

console.log(`DOM ${modName} ${modVer} supported?: ${conformTest}`);

// Log: "DOM HTML 2.0 supported?: true" (hasFeature always returns true)
```

**Warning:** Do not use this for feature detection. The `hasFeature()` method always returns true.

Notes
-----

 The W3C's DOM Level 1 Recommendation only specified the `hasFeature` method,
 which is one way to determine if a DOM module is supported by a browser (see example
 above and What does your user agent claim to support?). If available, other `DOMImplementation`
 methods provide services for controlling things outside of a single document. For
 example, the `DOMImplementation` interface includes a
 `createDocumentType` method with which DTDs can be created for one or more
 documents managed by the implementation.

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

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

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

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


Document: mozSetImageElement() method - Web APIs

Document: mozSetImageElement() method
=====================================

**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 **`Document.mozSetImageElement()`** method changes the
 element being used as the CSS background for a background with a given background
 element ID.

Syntax
------

```js
mozSetImageElement(imageElementId, imageElement)
```

### Parameters

* `imageElementId` is a string indicating the name of an element that has
 been specified as a background image using the `-moz-element` CSS
 function.
* `imageElement` is the new element to use as the background corresponding
 to that image element string. Specify `null` to remove the background
 element.
### Return value

None (`undefined`).

Examples
--------

 This example changes the background of a `<div>` block each time the
 block is clicked by the user.

View this example live.

```html
<style>
 #mybox {
 background-image: -moz-element(#canvasbg);
 text-align: center;
 width: 400px;
 height: 400px;
 cursor: pointer;
 }
</style>
```

The CSS defined by the `<style>` block above is used by our `<div>` to use an element with the id "canvasbg" as its background.

```js
let c = 0x00;
function clicked() {
  const canvas = document.createElement("canvas");
  canvas.setAttribute("width", 100);
  canvas.setAttribute("height", 100);

  const ctx = canvas.getContext("2d");
  ctx.fillStyle = `#${c.toString(16)}0000`;
  ctx.fillRect(25, 25, 75, 75);

  c += 0x11;
  if (c > 0xff) {
    c = 0x00;
  }

  document.mozSetImageElement("canvasbg", canvas);
}
```

 The code here is called each time the user clicks the `<div>` element.
 It creates a new `<canvas>` with the width and height set to 100
 pixels, then draws into it a 50 by 50 pixel square. Each time the function is called,
 the square is a different color (its red component is increased each time), so each time
 the user clicks the element, the background is filled with a brighter and brighter
 pattern of red tiles.

 Once the canvas is drawn, `document.mozSetImageElement()` is called to set
 the background for any CSS using the ID "canvasbg" as its background element ID to be
 our new canvas.

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

Not part of any specification.

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

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

See also
--------

* `-moz-element`


Document: createRange() method - Web APIs

Document: createRange() method
==============================

 The **`Document.createRange()`** method returns a new
 `Range` object.

Syntax
------

```js
createRange()
```

### Parameters

None.

### Return value

The created `Range` object.

Examples
--------

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

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

Notes
-----

 Once a `Range` is created, you need to set its boundary points before you
 can make use of most of its methods.

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

| Specification |
| --- |
| DOM Standard # dom-document-createrange |

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

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


Document: lastModified property - Web APIs

Document: lastModified property
===============================

 The **`lastModified`** property of the `Document`
 interface returns a string containing the date and local time on which the current document
 was last modified.

Value
-----

A string.

Examples
--------

### Simple usage

This example alerts the value of `lastModified`.

```js
alert(document.lastModified);
// returns: Tuesday, December 16, 2017 11:09:42
```

### Transforming lastModified into a Date object

This example transforms `lastModified` into a `Date` object.

```js
let oLastModif = new Date(document.lastModified);
```

### Transforming lastModified into milliseconds

 This example transforms `lastModified` into the number of milliseconds since
 January 1, 1970, 00:00:00, local time.

```js
let nLastModif = Date.parse(document.lastModified);
```

Notes
-----

 Note that as a string, `lastModified` cannot *easily* be used for
 comparing the modification dates of documents. Here is a possible example of how to show
 an alert message when the page changes (see also: JavaScript cookies API):

```js
// Match 'timestamp' in 'last\_modif=timestamp'
// e.g. '1687964614822' in 'last\_modif=1687964614822'
const pattern = /last\_modif\s\*=\s\*([^;]\*)/;

if (
  Date.parse(document.lastModified) >
  (parseFloat(document.cookie.match(pattern)?.[1]) || 0)
) {
  document.cookie = `last\_modif=${Date.now()}; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=${
 location.pathname
 }`;
  alert("This page has changed!");
}
```

…the same example, but skipping the first visit:

```js
const pattern = /last\_modif\s\*=\s\*([^;]\*)/;

const lastVisit = parseFloat(document.cookie.replace(pattern, "$1"));
const lastModif = Date.parse(document.lastModified);

if (Number.isNaN(lastVisit) || lastModif > lastVisit) {
  document.cookie = `last\_modif=${Date.now()}; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=${
 location.pathname
 }`;

  if (isFinite(lastVisit)) {
    alert("This page has been changed!");
  }
}
```

If you want to know whether an *external* page has changed, you can make a `HEAD` request using the `fetch()` API, and examine the `Last-Modified` response header.

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

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

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

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


Document: location property - Web APIs

Document: location property
===========================

 The **`Document.location`** read-only property returns a
 `Location` object, which contains information about the URL of the document
 and provides methods for changing that URL and loading another URL.

 Though `Document.location` is a *read-only* `Location`
 object, you can also assign a string to it. This means that you can
 work with document.location as if it were a string in most cases:
 `document.location = 'http://www.example.com'` is a synonym of
 `document.location.href = 'http://www.example.com'`. If you assign another
 string to it, browser will load the website you assigned.

 To retrieve just the URL as a string, the read-only `document.URL`
 property can also be used.

 If the current document is not in a browsing context, the returned value is
 `null`.

Value
-----

A `Location` object.

Examples
--------

```js
console.log(document.location);
// Prints a Location object to the console
```

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

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

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

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

See also
--------

* The interface of the returned value, `Location`
* A similar information, but attached to the browsing context,
 `Window.location`


Document: scripts property - Web APIs

Document: scripts property
==========================

 The **`scripts`** property of the `Document`
 interface returns a list of the `<script>`
 elements in the document. The returned object is an
 `HTMLCollection`.

Value
-----

 An `HTMLCollection`. You can use this just like an array to get all the
 elements in the list.

Examples
--------

This example looks to see if the page has any `<script>` elements.

```js
let scripts = document.scripts;

if (scripts.length) {
  alert("This page has scripts!");
}
```

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

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

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

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


Document: createAttribute() method - Web APIs

Document: createAttribute() method
==================================

 The **`Document.createAttribute()`** method creates a new
 attribute node, and returns it. The object created is a node implementing the
 `Attr` interface. The DOM does not enforce what sort of attributes can be
 added to a particular element in this manner.

**Note:** The string given in parameter is converted to lowercase.

Syntax
------

```js
createAttribute(name)
```

### Parameters

* `name` is a string containing the name of the attribute.
### Return value

A `Attr` node.

### Exceptions

`InvalidCharacterError` `DOMException`

Thrown if the `name` value is not a valid XML name; for example, it starts with a number, hyphen, or period, or contains characters other than alphanumeric characters, underscores, hyphens, or periods.

Examples
--------

```js
const node = document.getElementById("div1");
const a = document.createAttribute("my\_attrib");
a.value = "newVal";
node.setAttributeNode(a);
console.log(node.getAttribute("my\_attrib")); // "newVal"
```

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

| Specification |
| --- |
| DOM Standard # dom-document-createattribute |

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

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

See also
--------

* `Document.createAttributeNS()`
* `Document.createElement()`
* `Element.setAttribute()`
* `Element.setAttributeNode()`


Document: execCommand() method - Web APIs

Document: execCommand() 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.

The **`execCommand`** method implements multiple different commands. Some of them provide access to the clipboard, while others are for editing form inputs, `contenteditable` elements or entire documents (when switched to design mode).

To access the clipboard, the newer Clipboard API is recommended over `execCommand()`. However, there is no replacement for the editing commands: unlike direct DOM manipulation, modifications performed by `execCommand()` preserve the undo buffer (edit history).

Most commands affect the document's selection. For example, some commands (bold, italics, etc.) format the currently selected text, while others delete the selection, insert new elements (replacing the selection) or affect an entire line (indenting). Only the currently active editable element can be modified, but some commands (e.g. `copy`) can work without an editable element.

**Note:** Modifications performed by `execCommand()` may or may not trigger `beforeinput` and `input` events, depending on the browser and configuration. If triggered, the handlers for the events will run before `execCommand()` returns. Authors need to be careful about such recursive calls, especially if they call `execCommand()` in response to these events. From Firefox 82, nested `execCommand()` calls will always fail, see bug 1634262.

Syntax
------

```js
execCommand(aCommandName, aShowDefaultUI, aValueArgument)
```

### Parameters

`aCommandName`

A string specifying the name of the command to execute. The following commands are specified:

`backColor`

Changes the document background color. In `styleWithCss` mode, it affects the background color of the containing block instead. This requires a `<color>` value string to be passed in as a value argument.

`bold`

Toggles bold on/off for the selection or at the insertion point.

`contentReadOnly`

Makes the content document either read-only or editable. This requires a boolean true/false as the value argument.

`copy`

Copies the current selection to the clipboard. Conditions of having this behavior enabled vary from one browser to another, and have evolved over time. Check the compatibility table to determine if you can use it in your case.

`createLink`

Creates an hyperlink from the selection, but only if there is a selection. Requires a URI string as a value argument for the hyperlink's `href`. The URI must contain at least a single character, which may be whitespace.

`cut`

Removes the current selection and copies it to the clipboard. When this behavior is enabled varies between browsers, and its conditions have evolved over time. Check the compatibility table for usage details.

`decreaseFontSize`

Adds a `<small>` tag around the selection or at the insertion point.

`defaultParagraphSeparator`

Changes the paragraph separator used when new paragraphs are created in editable text regions. See Differences in markup generation for more details.

`delete`

Deletes the current selection.

`enableAbsolutePositionEditor`

Enables or disables the grabber that allows absolutely-positioned elements to be moved around. The grabber is disabled by default since Firefox 64 (Firefox bug 1490641).

`enableInlineTableEditing`

Enables or disables the table row/column insertion and deletion controls. The controls are disabled by default since Firefox 64 (Firefox bug 1490641).

`enableObjectResizing`

Enables or disables the resize handles on images, tables, and absolutely-positioned elements and other resizable objects. The handles are disabled by default since Firefox 64 (Firefox bug 1490641).

`fontName`

Changes the font name for the selection or at the insertion point. This requires a font name string (like `"Arial"`) as a value argument.

`fontSize`

Changes the font size for the selection or at the insertion point. This requires an integer from `1` - `7` as a value argument.

`foreColor`

Changes a font color for the selection or at the insertion point. This requires a hexadecimal color value string as a value argument.

`formatBlock`

Adds an HTML block-level element around the line containing the current selection, replacing the block element containing the line if one exists (in Firefox, `<blockquote>` is the exception — it will wrap any containing block element). Requires a tag-name string as a value argument. Virtually all block-level elements can be used. (Legacy Edge only supports heading tags `H1` – `H6`, `ADDRESS`, and `PRE`, which must be wrapped in angle brackets, such as `"<H1>"`.)

`forwardDelete`

Deletes the character ahead of the cursor's position, identical to hitting the Delete key on a Windows keyboard.

`heading`

Adds a heading element around a selection or insertion point line. Requires the tag-name string as a value argument (i.e., `"H1"`, `"H6"`). (Not supported by Safari.)

`hiliteColor`

Changes the background color for the selection or at the insertion point. Requires a color value string as a value argument. `useCSS` must be `true` for this to function.

`increaseFontSize`

Adds a `<big>` tag around the selection or at the insertion point.

`indent`

Indents the line containing the selection or insertion point. In Firefox, if the selection spans multiple lines at different levels of indentation, only the least indented lines in the selection will be indented.

`insertBrOnReturn`

Controls whether the Enter key inserts a `<br>` element, or splits the current block element into two.

`insertHorizontalRule`

Inserts a `<hr>` element at the insertion point, or replaces the selection with it.

`insertHTML`

Inserts an HTML string at the insertion point (deletes selection). Requires a valid HTML string as a value argument.

`insertImage`

Inserts an image at the insertion point (deletes selection). Requires a URL string for the image's `src` as a value argument. The requirements for this string are the same as `createLink`.

`insertOrderedList`

Creates a numbered ordered list for the selection or at the insertion point.

`insertUnorderedList`

Creates a bulleted unordered list for the selection or at the insertion point.

`insertParagraph`

Inserts a paragraph around the selection or the current line.

`insertText`

Inserts the given plain text at the insertion point (deletes selection).

`italic`

Toggles italics on/off for the selection or at the insertion point.

`justifyCenter`

Centers the selection or insertion point.

`justifyFull`

Justifies the selection or insertion point.

`justifyLeft`

Justifies the selection or insertion point to the left.

`justifyRight`

Right-justifies the selection or the insertion point.

`outdent`

Outdents the line containing the selection or insertion point.

`paste`

Pastes the clipboard contents at the insertion point (replaces current selection). Disabled for web content.

`redo`

Redoes the previous undo command.

`removeFormat`

Removes all formatting from the current selection.

`selectAll`

Selects all of the content of the editable region.

`strikeThrough`

Toggles strikethrough on/off for the selection or at the insertion point.

`subscript`

Toggles subscript on/off for the selection or at the insertion point.

`superscript`

Toggles superscript on/off for the selection or at the insertion point.

`underline`

Toggles underline on/off for the selection or at the insertion point.

`undo`

Undoes the last executed command.

`unlink`

Removes the anchor element from a selected hyperlink.

`useCSS`
Deprecated

Toggles the use of HTML tags or CSS for the generated markup. Requires a boolean true/false as a value argument.

**Note:** This argument is logically backwards (i.e., use `false` to use CSS,
 `true` to use HTML). This has been deprecated in favor of `styleWithCSS`.

`styleWithCSS`

Replaces the `useCSS` command. `true` modifies/generates `style` attributes in markup, false generates presentational elements.

`AutoUrlDetect`

Changes the browser auto-link behavior.

`aShowDefaultUI`

A boolean value indicating whether the default user interface should be shown. This is not implemented in Mozilla.

`aValueArgument`

For commands which require an input argument, is a string providing that information. For example, `insertImage` requires the URL of the image to insert. Specify `null` if no argument is needed.

### Return value

A boolean value that is `false` if the command is unsupported or disabled.

**Note:** `document.execCommand()` only returns
 `true` if it is invoked as part of a user interaction. You can't use it to
 verify browser support before calling a command.

Examples
--------

An example of how to use execCommand with contentEditable elements on CodePen.

### Using insertText

This example shows two very basic HTML editors, one using a `<textarea>` element and one using a `<pre>` element with the `contenteditable` attribute set.

Clicking the "Bold" or "Italic" buttons inserts the appropriate tags in the element, using `insertText` to preserve the edit history, so the user can undo the action.

#### HTML

```html
<h2>textarea</h2>

<div class="actions" data-for="textarea">
  <button data-el="b">Bold</button>
  <button data-el="i">Italic</button>
</div>

<textarea class="editarea">Some text.</textarea>

<h2>contenteditable</h2>

<div class="actions" data-for="pre">
  <button data-el="b">Bold</button>
  <button data-el="i">Italic</button>
</div>

<pre contenteditable="true" class="editarea">Some text.</pre>
```

#### JavaScript

```js
// Prepare action buttons
const buttonContainers = document.querySelectorAll(".actions");

for (const buttonContainer of buttonContainers) {
  const buttons = buttonContainer.querySelectorAll("button");
  const pasteTarget = buttonContainer.getAttribute("data-for");

  for (const button of buttons) {
    const elementName = button.getAttribute("data-el");
    button.addEventListener("click", () =>
      insertText(`<${elementName}></${elementName}>`, pasteTarget),
    );
  }
}

// Inserts text at cursor, or replaces selected text
function insertText(newText, selector) {
  const textarea = document.querySelector(selector);
  textarea.focus();

  let pasted = true;
  try {
    if (!document.execCommand("insertText", false, newText)) {
      pasted = false;
    }
  } catch (e) {
    console.error("error caught:", e);
    pasted = false;
  }

  if (!pasted) {
    console.error("paste unsuccessful, execCommand not supported");
  }
}
```

#### Result

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

This feature is not part of any current specification, but there is an unofficial draft attempting to specify it.

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

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

See also
--------

* Clipboard API
* `HTMLElement.contentEditable`
* `document.designMode`


Document: getElementsByClassName() method - Web APIs

Document: getElementsByClassName() method
=========================================

 The **`getElementsByClassName`** method of
 `Document` interface returns an array-like object
 of all child elements which have all of the given class name(s).

 When called on
 the `document` object, the complete document is searched, including the
 root node. You may also call `getElementsByClassName()` on any element; it will return only elements which are
 descendants of the specified root element with the given class name(s).

**Warning:** This is a live `HTMLCollection`. Changes in the DOM will
 reflect in the array as the changes occur. If an element selected by this array no
 longer qualifies for the selector, it will automatically be removed. Be aware of this
 for iteration purposes.

Syntax
------

```js
getElementsByClassName(names)
```

### Parameters

`names`

A string representing the class name(s) to match; multiple class names are separated by whitespace.

### Return value

A live `HTMLCollection` of found elements.

Examples
--------

Get all elements that have a class of 'test':

```js
document.getElementsByClassName("test");
```

Get all elements that have both the 'red' and 'test' classes:

```js
document.getElementsByClassName("red test");
```

 Get all elements that have a class of 'test', inside of an element that has the ID of
 'main':

```js
document.getElementById("main").getElementsByClassName("test");
```

 Get the first element with a class of 'test', or `undefined` if there is no
 matching element:

```js
document.getElementsByClassName("test")[0];
```

 We can also use methods of Array.prototype on any `HTMLCollection` by
 passing the `HTMLCollection` as the method's *this* value. Here
 we'll find all div elements that have a class of 'test':

```js
const testElements = document.getElementsByClassName("test");
const testDivs = Array.prototype.filter.call(
  testElements,
  (testElement) => testElement.nodeName === "DIV",
);
```

### Get the first element whose class is 'test'

This is the most commonly used method of operation.

```html
<html lang="en">
  <body>
    <div id="parent-id">
      <p>hello world 1</p>
      <p class="test">hello world 2</p>
      <p>hello world 3</p>
      <p>hello world 4</p>
    </div>

    <script>
 const parentDOM = document.getElementById("parent-id");

 const test = parentDOM.getElementsByClassName("test"); // a list of matching elements, \*not\* the element itself
 console.log(test); // HTMLCollection[1]

 const testTarget = parentDOM.getElementsByClassName("test")[0]; // the first element, as we wanted
 console.log(testTarget); // <p class="test">hello world 2</p>
 </script>
  </body>
</html>
```

### Multiple Classes Example

`document.getElementsByClassName` works very similarly to
 `document.querySelector` and `document.querySelectorAll`. Only
 elements with ALL of the classNames specified are selected.

#### HTML

```html
<span class="orange fruit">Orange Fruit</span>
<span class="orange juice">Orange Juice</span>
<span class="apple juice">Apple Juice</span>
<span class="foo bar">Something Random</span>
<textarea id="resultArea" style="width:98%;height:7em"></textarea>
```

#### JavaScript

```js
// getElementsByClassName only selects elements that have both given classes
const allOrangeJuiceByClass = document.getElementsByClassName("orange juice");
let result = "document.getElementsByClassName('orange juice')";
for (let i = 0; i < allOrangeJuiceByClass.length; i++) {
  result += `\n ${allOrangeJuiceByClass[i].textContent}`;
}

// querySelector only selects full complete matches
const allOrangeJuiceQuery = document.querySelectorAll(".orange.juice");
result += "\n\ndocument.querySelectorAll('.orange.juice')";
for (let i = 0; i < allOrangeJuiceQuery.length; i++) {
  result += `\n ${allOrangeJuiceQuery[i].textContent}`;
}

document.getElementById("resultArea").value = result;
```

#### Result

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

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

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

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


Document: rootElement property - Web APIs

Document: rootElement property
==============================

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

**`Document.rootElement`** returns the `Element`
 that is the root element of the `document` if it is an
 `<svg>` element, otherwise `null`. It is deprecated in favor of
 `Document.documentElement`, which returns the root element for all
 documents.

Value
-----

For SVG elements, the `Element` that is the root element of the `document`; otherwise `null`.

 If the document is a non-empty SVG document, then the `rootElement` will be
 an `SVGSVGElement`, identical to the `documentElement`.

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

| Specification |
| --- |
| Scalable Vector Graphics (SVG) 2 # \_\_svg\_\_SVGDocument\_\_rootElement |

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

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


Document: createEvent() method - Web APIs

Document: createEvent() method
==============================

**Warning:** Many methods used with `createEvent`, such as `initCustomEvent`, are deprecated.
 Use event constructors instead.

 Creates an event of the type specified. The
 returned object should be first initialized and can then be passed to
 `EventTarget.dispatchEvent`.

Syntax
------

```js
createEvent(type)
```

### Parameters

`type`

A string that represents the type of event to be created. Possible event types include `"UIEvents"`, `"MouseEvents"`, `"MutationEvents"`, and `"HTMLEvents"`. See Notes section for details.

### Return value

An Event object.

Examples
--------

```js
// Create the event.
const event = document.createEvent("Event");

// Define that the event name is 'build'.
event.initEvent("build", true, true);

// Listen for the event.
elem.addEventListener(
  "build",
  (e) => {
    // e.target matches elem
  },
  false,
);

// Target can be any Element or other EventTarget.
elem.dispatchEvent(event);
```

Notes
-----

 Event type strings suitable for passing to `createEvent()` are listed in the
 DOM standard — see the table in step 2. Bear in mind that most event objects now have constructors, which
 are the modern recommended way to create event object instances.

Gecko supports some non-standard event object aliases, which are listed below.

| Event Module | Standard event object | Gecko also supports |
| --- | --- | --- |
| Text event module | `TextEvent` | `TextEvents` |
| Keyboard event module | `KeyboardEvent` | `KeyEvents` |
| Basic events module | `Event` | `Events` |

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

| Specification |
| --- |
| DOM Standard # dom-document-createevent |

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

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

See also
--------

* Creating and triggering events


Document: pictureInPictureElement property - Web APIs

Document: pictureInPictureElement property
==========================================

 The read-only **`pictureInPictureElement`** property of the `Document`
 interface returns the `Element` that is currently being
 presented in picture-in-picture mode in this document, or `null` if
 picture-in-picture mode is not currently in use.

 Although this property is read-only, it will not throw if it is modified (even in
 strict mode); the setter is a no-operation and will be ignored.

Value
-----

 A reference to the `Element` object that's currently in
 picture-in-picture mode; if picture-in-picture mode isn't currently in use by the
 `document`, the returned value is `null`.

Examples
--------

 This example presents a function, `exitPictureInPicture()`,
 which tests the value returned by `pictureInPictureElement`. If the document
 is in picture-in-picture mode (`pictureInPictureElement` isn't
 `null`), `Document.exitPictureInPicture()` is run to exit
 picture-in-picture mode.

```js
function exitPictureInPicture() {
  if (document.pictureInPictureElement) {
    document.exitPictureInPicture();
  }
}
```

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

| Specification |
| --- |
| Picture-in-Picture # ref-for-dom-documentorshadowroot-pictureinpictureelement①⑤ |

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

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

See also
--------

* `HTMLVideoElement.requestPictureInPicture()`
* `HTMLVideoElement.disablePictureInPicture`
* `Document.pictureInPictureEnabled`
* `Document.exitPictureInPicture()`
* `:picture-in-picture`


Document: Document() constructor - Web APIs

Document: Document() constructor
================================

 The **`Document`** constructor creates a new
 `Document` object that is a web page loaded in the browser and serving as
 an entry point into the page's content.

Syntax
------

```js
new Document()
```

### Parameters

None.

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

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

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

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


Document: hidden property - Web APIs

Document: hidden property
=========================

 The **`Document.hidden`** read-only property returns a Boolean
 value indicating if the page is considered hidden or not.

The `Document.visibilityState` property provides an alternative way to determine whether the page is hidden.

Value
-----

A Boolean value, `true` if the page is hidden, and `false` otherwise.

Examples
--------

```js
document.addEventListener("visibilitychange", () => {
  console.log(document.hidden);
  // Modify behavior…
});
```

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

| Specification |
| --- |
| HTML Standard # dom-document-hidden |

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

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

See also
--------

* `Document.visibilityState`


Document: fullscreenerror event - Web APIs

Document: fullscreenerror event
===============================

The `fullscreenerror` event is fired when the browser cannot switch to fullscreen mode.

As with the `fullscreenchange` event, two `fullscreenerror` events are fired; the first is sent to the `Element` which failed to change modes, and the second is sent to the `Document` which owns that element.

For some reasons that switching into fullscreen mode might fail, see the guide to the Fullscreen API.

This event is not cancelable.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

```js
const requestor = document.querySelector("div");

function handleError(event) {
  console.error("an error occurred changing into fullscreen");
  console.log(event);
}

document.addEventListener("fullscreenerror", handleError);
// or
document.onfullscreenerror = handleError;

requestor.requestFullscreen();
```

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

| Specification |
| --- |
| Fullscreen API Standard # handler-document-onfullscreenerror |

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

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

See also
--------

* `fullscreenchange`
* `Element`: `fullscreenerror` event
* Fullscreen API
* Guide to the Fullscreen API