Document: querySelector() method - Web APIs

Document: querySelector() method
================================

 The `Document` method **`querySelector()`**
 returns the first `Element` within the document that matches the specified
 selector, or group of selectors. If no matches are found, `null` is returned.

**Note:** The matching is done using depth-first pre-order traversal of
 the document's nodes starting with the first element in the document's markup and
 iterating through sequential nodes by order of the number of child nodes.

Syntax
------

```js
querySelector(selectors)
```

### Parameters

`selectors`

 A string containing one or more selectors to match. This string
 must be a valid CSS selector string; if it isn't, a `SyntaxError` exception
 is thrown. See Locating DOM elements using selectors for more about selectors and how to manage them.

**Note:** Characters that are not part of standard CSS syntax must be
 escaped using a backslash character. Since JavaScript also uses backslash escaping, be
 especially careful when writing string literals using these characters. See
 Escaping special characters for more information.

### Return value

 An `Element` object representing the first element in the document
 that matches the specified set of CSS selectors, or `null` is returned if there are no matches.

 If you need a list of all elements matching the specified selectors, you should use
 `querySelectorAll()` instead.

### Exceptions

`SyntaxError` `DOMException`

Thrown if the syntax of the specified *selectors* is invalid.

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

 If the specified selector matches an ID that is incorrectly used more than once in the
 document, the first element with that ID is returned.

CSS pseudo-elements will never return
 any elements, as specified in the Selectors API.

### Escaping special characters

 To match against an ID or selectors that do not follow standard CSS syntax (by using a
 colon or space inappropriately, for example), you must escape the character with a
 backslash ("`\`"). As the backslash is also an escape character in
 JavaScript, if you are entering a literal string, you must escape it *twice*
 (once for the JavaScript string, and another time for `querySelector()`):

```html
<div id="foo\bar"></div>
<div id="foo:bar"></div>

<script>
 console.log("#foo\bar"); // "#fooar" (\b is the backspace control character)
 document.querySelector("#foo\bar"); // Does not match anything

 console.log("#foo\\bar"); // "#foo\bar"
 console.log("#foo\\\\bar"); // "#foo\\bar"
 document.querySelector("#foo\\\\bar"); // Match the first div

 document.querySelector("#foo:bar"); // Does not match anything
 document.querySelector("#foo\\:bar"); // Match the second div
</script>
```

Examples
--------

### Finding the first element matching a class

 In this example, the first element in the document with the class
 "`myclass`" is returned:

```js
const el = document.querySelector(".myclass");
```

### Complex selectors

 Selectors can also be really powerful, as demonstrated in the following example. Here,
 the first `<input>` element with the name "login"
 (`<input name="login"/>`) located inside a `<div>` whose
 class is "user-panel main" (`<div class="user-panel main">`) in the
 document is returned:

```js
const el = document.querySelector("div.user-panel.main input[name='login']");
```

### Negation

As all CSS selector strings are valid, you can also negate selectors:

```js
const el = document.querySelector(
  "div.user-panel:not(.main) input[name='login']",
);
```

 This will select an input with a parent div with the `user-panel` class but
 not the `main` class.

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

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

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

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

See also
--------

* Locating DOM elements using selectors
* `Element.querySelector()`
* `Document.querySelectorAll()`
* `Element.querySelectorAll()`


Document: fullscreenEnabled property - Web APIs

Document: fullscreenEnabled property
====================================

 The read-only **`fullscreenEnabled`**
 property on the `Document` interface indicates whether or not fullscreen
 mode is available.

 fullscreen mode is available only for a page that has no
 windowed plug-ins in any of its documents, and if all `<iframe>` elements
 which contain the document have their `allowfullscreen`
 attribute set.

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

 A boolean value which is `true` if the document and the
 elements within can be placed into fullscreen mode by calling
 `Element.requestFullscreen()`. If fullscreen mode isn't available, this
 value is `false`.

Examples
--------

 In this example, before attempting to request fullscreen mode for a
 `<video>` element, the value of `fullscreenEnabled` is
 checked, in order to avoid making the attempt when not available.

```js
function requestFullscreen() {
  if (document.fullscreenEnabled) {
    videoElement.requestFullscreen();
  } else {
    console.log("Your browser cannot use fullscreen right now");
  }
}
```

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

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

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()`
* `Document.fullscreenElement`
* `:fullscreen` and `::backdrop`
* The `<iframe>` `allowfullscreen`
 attribute


Document: releaseCapture() method - Web APIs

Document: releaseCapture() 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 **`releaseCapture()`** method releases mouse capture if
 it's currently enabled on an element within this document.
 Once mouse capture is released, mouse events will no longer all be directed to the element on which capture is enabled.

Enabling mouse capture on an element is done by calling `element.setCapture()`.

Syntax
------

```js
releaseCapture()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

 See the example for
 `element.setCapture()`.

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

* `element.setCapture()`


Document: close() method - Web APIs

Document: close() method
========================

 The **`Document.close()`** method finishes writing to a
 document, opened with `Document.open()`.

Syntax
------

```js
close()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

```js
// Open a document to write to it
document.open();

// Write the content of the document
document.write("<p>The one and only content.</p>");

// Close the document
document.close();
```

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

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

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

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


Document: fullscreenchange event - Web APIs

Document: fullscreenchange event
================================

The `fullscreenchange` event is fired immediately after the browser switches into or out of fullscreen mode.

The event is sent to the `Element` that is transitioning into or out of fullscreen mode, and this event then bubbles up to the `Document`.

To find out whether the `Element` is entering or exiting fullscreen mode, check the value of `Document.fullscreenElement`: if this value is `null` then the element is exiting fullscreen mode, otherwise it is entering fullscreen mode.

This event is not cancelable.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

### Logging `fullscreenchange` events

In this example, a handler for the `fullscreenchange` event is added to the `Document`.

If the user clicks on the "Toggle Fullscreen Mode" button, the `click` handler will toggle fullscreen mode for the `div`. If `document.fullscreenElement` has a value it will exit fullscreen mode. If not, the div will be placed into fullscreen mode.

Remember that by the time the `fullscreenchange` event is handled, the status of the element has already changed. So if the change is to fullscreen mode, `document.fullscreenElement` will point to the element that is now in fullscreen mode. On the other hand, if `document.fullscreenElement` is null, fullscreen mode has been canceled.

What that means to the example code is that, if an element is currently in fullscreen mode, the `fullscreenchange` handler logs the `id` of the fullscreen element to the console. If `document.fullscreenElement` is null, the code logs a message that the change is to leave fullscreen mode.

#### HTML

```html
<h1>fullscreenchange event example</h1>
<div id="fullscreen-div">
  <button id="toggle-fullscreen">Toggle Fullscreen Mode</button>
  <pre id="logger"></pre>
</div>
```

#### CSS

```css
\* {
  box-sizing: border-box;
}

#fullscreen-div {
  height: 150px;
  padding: 1rem;
  background-color: pink;
}

#logger {
  height: 80px;
  padding: 0 0.5rem;
  background-color: white;
  overflow: scroll;
}
```

#### JavaScript

```js
const logger = document.querySelector("#logger");
const fullScreenElement = document.querySelector("#fullscreen-div");

function log(message) {
  logger.textContent = `${logger.textContent}\n${message}`;
}

function fullscreenchanged(event) {
  // document.fullscreenElement will point to the element that
  // is in fullscreen mode if there is one. If there isn't one,
  // the value of the property is null.
  if (document.fullscreenElement) {
    log(`Element: ${document.fullscreenElement.id} entered fullscreen mode.`);
  } else {
    log("Leaving fullscreen mode.");
  }
}

document.addEventListener("fullscreenchange", fullscreenchanged);

// When the toggle button is clicked, enter/exit fullscreen
document.getElementById("toggle-fullscreen").addEventListener("click", () => {
  if (document.fullscreenElement) {
    // exitFullscreen is only available on the Document object.
    document.exitFullscreen();
  } else {
    fullScreenElement.requestFullscreen();
  }
});
```

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

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

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

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

See also
--------

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


Document: importNode() method - Web APIs

Document: importNode() method
=============================

 The `Document` object's **`importNode()`** method creates a copy of a
 `Node` or `DocumentFragment` from another document, to be
 inserted into the current document later.

 The imported node is not yet included in the document tree. To include it, you need to
 call an insertion method such as `appendChild()` or
 `insertBefore()` with a node that *is*
 currently in the document tree.

 Unlike `document.adoptNode()`, the original node is not removed from its
 original document. The imported node is a clone of the original.

Syntax
------

```js
importNode(externalNode)
importNode(externalNode, deep)
```

### Parameters

`externalNode`

 The external `Node` or `DocumentFragment` to import into
 the current document.

`deep` Optional

 A boolean flag, whose default value is `false`,
 which controls whether to include the entire DOM subtree
 of the `externalNode` in the import.

* If `deep` is set to `true`, then
 `externalNode` and all of its descendants are copied.
* If `deep` is set to `false`, then only
 `externalNode` is imported — the new node has no children.

### Return value

The copied `importedNode` in the scope of the importing document.

**Note:** `importedNode`'s `Node.parentNode` is `null`, since it has not yet been inserted into the document tree!

Examples
--------

```js
const iframe = document.querySelector("iframe");
const oldNode = iframe.contentWindow.document.getElementById("myNode");
const newNode = document.importNode(oldNode, true);
document.getElementById("container").appendChild(newNode);
```

Notes
-----

Before they can be inserted into the current document, nodes from external documents should either be:

* cloned using `document.importNode()`; or
* adopted using `document.adoptNode()`.

**Note:** Although Firefox doesn't currently enforce this rule, we encourage you to follow this rule for improved future compatibility.

For more on the `Node.ownerDocument` issues, see the W3C DOM FAQ.

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

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

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

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

See also
--------

* `document.adoptNode()`, which behaves very similar to this method
* `Node.appendChild()`
* `Node.insertBefore()`


Document: fgColor property - Web APIs

Document: fgColor 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.

**`fgColor`** gets/sets the foreground color, or text 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.fgColor = "white";
document.bgColor = "darkblue";
```

Notes
-----

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

`document.fgColor` is deprecated in DOM Level 2 HTML. The recommended alternative is the CSS property `color`
 (e.g., `document.body.style.color = "red"`).

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

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

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


Document: readystatechange event - Web APIs

Document: readystatechange event
================================

The **`readystatechange`** event is fired when the `readyState` attribute of a document has changed.

This event is not cancelable and does not bubble.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

### 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>
```

#### CSS
```

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 = `${log.textContent}load\n`;
});

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

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

#### Result

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

| Specification |
| --- |
| HTML Standard # event-readystatechange |

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

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

See also
--------

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


Document: selectionchange event - Web APIs

Document: selectionchange event
===============================

The **`selectionchange`** event of the Selection API is fired when the current `Selection` of a `Document` is changed.

This event is not cancelable and does not bubble.

The event can be handled by adding an event listener for `selectionchange` or using the `onselectionchange` event handler.

**Note:** This event is not quite the same as the `selectionchange` events fired when the text selection in an `<input>` or `<textarea>` element is changed. See `HTMLInputElement.selectionchange_event` for more details.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

```js
// addEventListener version
document.addEventListener("selectionchange", () => {
  console.log(document.getSelection());
});

// onselectionchange version
document.onselectionchange = () => {
  console.log(document.getSelection());
};
```

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

| Specification |
| --- |
| Selection API # selectionchange-event |
| Selection API # dom-globaleventhandlers-onselectionchange |

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

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

See also
--------

* `selectstart`
* `Document.getSelection()`
* `Selection`


Document: childElementCount property - Web APIs

Document: childElementCount property
====================================

 The **`Document.childElementCount`** read-only property
 returns the number of child elements of the document.

To get the number of children of a specific element, see `Element.childElementCount`.

Value
-----

A number.

Examples
--------

```js
document.children;
// HTMLCollection, usually containing an <html> element, the document's only child

document.childElementCount;
// 1
```

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

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

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

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

See also
--------

* `Element.childElementCount`
* `DocumentFragment.childElementCount`


Document: hasStorageAccess() method - Web APIs

Document: hasStorageAccess() method
===================================

The **`hasStorageAccess()`** method of the `Document` interface returns a `Promise` that resolves with a boolean value indicating whether the document has access to third-party, unpartitioned cookies.

This method is part of the Storage Access API.

Syntax
------

```js
hasStorageAccess()
```

### Parameters

None.

### Return value

A `Promise` that resolves with a boolean value indicating whether the document has access to third-party cookies — `true` if it does, and `false` if not.

The result returned by this method can be inaccurate in a couple of circumstances:

1. The user may have active browser settings that block third-party cookies; in this case, `true` may be returned even though third-party cookies are still inaccessible. To handle such a situation, you should gracefully handle any errors resulting in cookie values being unretrievable; for example, inform the user that access to their personalized settings is blocked and invite them to sign in again to use them.
2. The browser might not block third-party cookie access by default; in this case, `false` may be returned even though third-party cookies are accessible, and storage access wouldn't need to be requested (i.e., via `Document.requestStorageAccess()`). To get around this issue, you could query `Document.cookie` to find out whether your cookies are accessible, and call `Document.requestStorageAccess()` if they are not.

**Note:** If the promise gets resolved and a user gesture event was being processed when the function was originally called, the resolve handler will run as if a user gesture was being processed, so it will be able to call APIs that require user activation.

### Exceptions

`InvalidStateError` `DOMException`

Thrown if the current `Document` is not yet active.

Examples
--------

```js
document.hasStorageAccess().then((hasAccess) => {
  if (hasAccess) {
    // storage access has been granted already.
  } else {
    // storage access hasn't been granted already;
    // you may want to call requestStorageAccess().
  }
});
```

**Note:** See Using the Storage Access API for a more complete example.

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

| Specification |
| --- |
| The Storage Access API # dom-document-hasstorageaccess |

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

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

See also
--------

* `Document.requestStorageAccess()`, `Document.requestStorageAccessFor()`
* Using the Storage Access API
* Introducing Storage Access API (WebKit blog)


Document: requestStorageAccessFor() method - Web APIs

Document: requestStorageAccessFor() method
==========================================

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

The **`requestStorageAccessFor()`** method of the `Document` interface allows top-level sites to request third-party cookie access on behalf of embedded content originating from another site in the same related website set. It returns a `Promise` that resolves if the access was granted, and rejects if access was denied.

Syntax
------

```js
requestStorageAccessFor(requestedOrigin)
```

### Parameters

`requestedOrigin`

A string representing the URL of the origin you are requesting third-party cookie access for.

### Return value

A `Promise` that fulfills with `undefined` if the access to third-party cookies was granted and rejects if access was denied.

`requestStorageAccessFor()` requests are automatically denied unless the embedded content is currently processing a user gesture such as a tap or click (transient activation), or unless permission was already granted previously. If permission was not previously granted, they must run inside a user gesture-based event handler. The user gesture behavior depends on the state of the promise:

* If the promise resolves (i.e., permission was granted), then the user gesture has not been consumed, so the script can subsequently call APIs requiring a user gesture.
* If the promise is rejected (i.e., permission was not granted), then the user gesture has been consumed, so the script can't do anything that requires a gesture. This prevents scripts from calling `requestStorageAccessFor()` again if permission is denied.
### Exceptions

`InvalidStateError` `DOMException`

Thrown if the current `Document` is not yet active.

`NotAllowedError` `DOMException`

Thrown if:

* The document's window is not a secure context.
* The document is not the top-level document.
* The document has a `null` origin.
* The supplied `requestedOrigin` is opaque.
* The top-level and embedded sites are not in the same related website set.
* The embedding `<iframe>` is sandboxed, and the `allow-storage-access-by-user-activation` token is not set.
* Usage is blocked by a `storage-access` Permissions Policy.
* Usage is denied by the user agent's permission request to use the API.

`TypeError`

Thrown if `requestedOrigin` is not a valid URL.

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

The `requestStorageAccessFor()` method addresses challenges in adopting the Storage Access API on top-level sites that use cross-site images or scripts requiring cookies. It is relevant to user agents that by default block access to third-party, unpartitioned cookies to improve privacy (e.g. to prevent tracking), and is a proposed extension of the Storage Access API.

`requestStorageAccessFor()` can enable third-party cookie access for cross-site resources directly embedded into a top-level site that are unable to request storage access themselves, for example `<img>` elements. Cross-site content embedded in `<iframe>`s that has its own logic and resources and needs third-party cookie access should request storage access via `Document.requestStorageAccess()`.

To check whether permission to access third-party cookies has already been granted via `requestStorageAccessFor()`, you can call `Permissions.query()`, specifying the feature name `"top-level-storage-access"`. This is different from the feature name used for the regular `Document.requestStorageAccess()` method, which is `"storage-access"`.

The `Permissions.query()` call must specify the embedded origin; for example:

```js
navigator.permissions.query({
  name: "top-level-storage-access",
  requestedOrigin: "https://www.example.com",
});
```

**Note:** Usage of this feature may be blocked by a `storage-access` Permissions Policy set on your server (the same one that controls the rest of the Storage Access API). In addition, the document must pass additional browser-specific checks such as allowlists, blocklists, on-device classification, user settings, or anti-clickjacking heuristics.

Examples
--------

```js
function rSAFor() {
  if ("requestStorageAccessFor" in document) {
    document.requestStorageAccessFor("https://example.com").then(
      (res) => {
        // Use storage access
        doThingsWithCookies();
      },
      (err) => {
        // Handle errors
      },
    );
  }
}
```

After a successful `requestStorageAccessFor()` call, cross-site requests will include cookies if they include CORS / `crossorigin`, so sites may want to wait before triggering a request. Such requests must use the `credentials: "include"` option and resources must include the `crossorigin="use-credentials"` attribute.

For example:

```js
function checkCookie() {
  fetch("https://example.com/getcookies.json", {
    method: "GET",
    credentials: "include",
  })
    .then((response) => response.json())
    .then((json) => {
      // Do something
    });
}
```

**Note:** See Using the Storage Access API for a more complete example.

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

| Specification |
| --- |
| requestStorageAccessFor API # dom-document-requeststorageaccessfor |

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

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

See also
--------

* `Document.hasStorageAccess()`, `Document.requestStorageAccess()`
* Using the Storage Access API
* Introducing Storage Access API (WebKit blog)


Document: adoptNode() method - Web APIs

Document: adoptNode() method
============================

**`Document.adoptNode()`** transfers a node from another document into the method's
 document. The adopted node and its subtree are removed from their original document (if
 any), and their `ownerDocument` is changed to the
 current document. The node can then be inserted into the current document.

Syntax
------

```js
adoptNode(externalNode)
```

### Parameters

`externalNode`

The node from another document to be adopted.

### Return value

The copied `importedNode` in the scope of the importing document.

 After calling this method, `importedNode` and
 `externalNode` are the same object.

**Note:** `importedNode`'s
 `Node.parentNode` is `null`, since it has not yet been
 inserted into the document tree!

Examples
--------

```js
const iframe = document.querySelector("iframe");
const iframeImages = iframe.contentDocument.querySelectorAll("img");
const newParent = document.getElementById("images");

iframeImages.forEach((imgEl) => {
  newParent.appendChild(document.adoptNode(imgEl));
});
```

Notes
-----

 Before they can be inserted into the current document, nodes from external documents
 should either be:

* cloned using `document.importNode()`; or
* adopted using `document.adoptNode()`.

**Note:** Although Firefox doesn't currently enforce this rule,
 we encourage you to follow this rule for improved future compatibility.

For more on the `Node.ownerDocument` issues, see the W3C DOM FAQ.

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

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

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

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

See also
--------

* `document.importNode()`


Document: linkColor property - Web APIs

Document: linkColor 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 **`Document.linkColor`** property gets/sets the color of
 links within the document.

 This property is deprecated. As an alternative, you can set the CSS
 `color` property on either HTML anchor links (`<a>`) or on
 `:link` pseudo-classes. Another alternative is
 `document.body.link`, although this is deprecated in HTML 4.01.

Value
-----

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

Examples
--------

```js
document.linkColor = "blue";
```

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

HTML5

`Document.linkColor` is deprecated in DOM Level 2 HTML.

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

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

 The default value for this property in Mozilla Firefox is blue (`#0000ee` in
 hexadecimal).

See also
--------

* `document.vlinkColor`
* `document.alinkColor`


Document: pictureInPictureEnabled property - Web APIs

Document: pictureInPictureEnabled property
==========================================

 The read-only
 **`pictureInPictureEnabled`** property of the
 `Document` interface indicates whether or not picture-in-picture mode is
 available.

 Picture-in-Picture mode is available by default unless specified
 otherwise by a Permissions-Policy.

 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 boolean value, which is `true` if a video can enter
 picture-in-picture and be displayed in a floating window by calling
 `HTMLVideoElement.requestPictureInPicture()`. If picture-in-picture mode isn't
 available, this value is `false`.

Examples
--------

 In this example, before attempting to enter picture-in-picture mode for a
 `<video>` element the value of `pictureInPictureEnabled` is
 checked, to avoid making the call if the feature is not available.

```js
function requestPictureInPicture() {
  if (document.pictureInPictureEnabled) {
    videoElement.requestPictureInPicture();
  } else {
    console.log("Your browser cannot use picture-in-picture right now");
  }
}
```

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

| Specification |
| --- |
| Picture-in-Picture # ref-for-dom-document-pictureinpictureenabled |

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

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

See also
--------

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


Document: scrollingElement property - Web APIs

Document: scrollingElement property
===================================

 The **`scrollingElement`** read-only property of the
 `Document` interface returns a reference to the `Element` that
 scrolls the document. In standards mode, this is the root element of the
 document, `document.documentElement`.

 When in quirks mode, the `scrollingElement` attribute returns the HTML
 `body` element if it exists and is potentially scrollable, otherwise it returns null.

Value
-----

The `Element` that scrolls the document, usually the root element (unless not in standard mode).

Examples
--------

```js
const scrollElm = document.scrollingElement;
scrollElm.scrollTop = 0;
```

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

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

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

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


Document: replaceChildren() method - Web APIs

Document: replaceChildren() method
==================================

 The **`Document.replaceChildren()`** method replaces the
 existing children of a `Document` with a specified new set of children.

Syntax
------

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

### Parameters

`param1`, …, `paramN`

 A set of `Node` or string objects to replace the
 `Document`'s existing children with. If no replacement objects are
 specified, then the `Document` is emptied of all child nodes.

### Return value

None (`undefined`).

### Exceptions

`HierarchyRequestError` `DOMException`

Thrown if the constraints of the node tree are violated.

Examples
--------

### Emptying a document

`replaceChildren()` provides a very convenient mechanism for emptying a document
 of all its children. You call it on the document without any argument specified:

```js
document.replaceChildren();
document.children; // HTMLCollection []
```

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

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

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

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

See also
--------

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


Document: domain property - Web APIs

Document: domain 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 **`domain`** property of the `Document`
 interface gets/sets the domain portion of the origin of the current
 document, as used by the same-origin policy.

Value
-----

A string.

### Exceptions

`SecurityError` `DOMException`

Use of this feature was blocked by a Permissions Policy.

Examples
--------

### Getting the domain

 For code running at the URL `https://developer.mozilla.org/en-US/docs/Web`,
 this example would set `currentDomain` to the string
 "`developer.mozilla.org`".

```js
const currentDomain = document.domain;
```

 The getter for this property returns the domain portion of the current document's
 origin. In most cases, this will be the hostname portion of the document's URL. However,
 there are some exceptions:

* If the page has an opaque origin, e.g. for a page with a data URL, then it will
 return the empty string.
* If the `document.domain` setter has been used, then
 it will return the value that was set.

 Although the getter is not dangerous in the same way that the setter is, it is likely
 simpler and more useful to use the `Location.hostname` property instead.
 Then you can avoid `document.domain` entirely:

```js
const currentHostname = location.hostname;
```

 For the URL `https://developer.mozilla.org/en-US/docs/Web`,
 `currentHostname` is also the string "`developer.mozilla.org`".
 Other alternatives that provide slightly different information are
 `Location.host`, which includes the port, and
 `origin`, which provides the full origin.

### Setting the domain

```js
document.domain = domainString;
```

 The setter for this property can be used to *change* a page's
 origin, and thus modify how certain security checks are performed. It
 can only be set to the same or a parent domain. For example, if
 `https://a.example.com` and `https://b.example.com` both use

```js
document.domain = "example.com";
```

 then they have both modified their origin to have the same domain, and they can now
 access each other's DOM directly—despite being cross-origin, which would normally
 prevent such access.

 Note that setting `document.domain` to its current value is not a no-op. It
 still changes the origin. For example, if one page sets

```js
document.domain = document.domain;
```

 then it will be counted as cross-origin from any other normally-same-origin pages that
 have not done the same thing.

#### Deprecation

 The `document.domain` setter is deprecated. It undermines the security
 protections provided by the same origin policy, and complicates the origin model in browsers, leading to
 interoperability problems and security bugs.

 Attempting to set `document.domain` is dangerous. It opens up full access to
 a page's DOM from *all* subdomains, which is likely not what is intended. It
 also removes the port component from the origin, so now your page can be accessed by
 other pages with the same IP address or same host component, even on a different port.

 This is especially insecure on shared hosting. For example, another shared hosting
 customer is able to host a site at the same IP address but on a different port, then
 setting `document.domain` will remove the same-origin protection that
 normally protects you from that other customer's site accessing your site's data.

 Similar problems occur with shared hosting sites that give each customer a different
 subdomain. If a site sets `document.domain`, any other customer on a
 different subdomain can now do the same thing, and start accessing the data of the
 original site.

 Instead of using `document.domain` to facilitate cross-origin communication,
 you should use `Window.postMessage` to send an asynchronous message to the
 other origin. This controlled access via message-passing is much more secure than the
 blanket exposure of all data caused by `document.domain`.

#### Failures

 The setter will throw a "`SecurityError`" `DOMException` in
 several cases:

* The `document-domain`
`Permissions-Policy` is disabled.
* The document is inside a sandboxed `<iframe>`.
* The document has no browsing context.
* The document's effective domain is `null`.
* The given value is neither the same as the page's current hostname, nor a parent
 domain of it.

 As an example of this last failure case, trying to set `document.domain` to
 `"example.org"` when on `https://example.com/` will throw.

 Additionally, as part of its deprecation, it will do nothing when combined with certain
 modern isolation features:

* If used on a cross-origin isolated page, i.e. one that uses the appropriate values
 for the `Cross-Origin-Opener-Policy` and
 `Cross-Origin-Embedder-Policy` HTTP headers
* If used on an origin-isolated page, i.e. one that uses the
 `Origin-Isolation` HTTP header

 Finally, setting `document.domain` does not change the origin used for
 origin-checks by some Web APIs, preventing sub-domain access via this mechanism.
 Affected APIs include (but are not limited to):
 `Window.localStorage`, `IndexedDB_API`, `BroadcastChannel`, `SharedWorker` .

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

| Specification |
| --- |
| HTML Standard # relaxing-the-same-origin-restriction |

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

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

See also
--------

* Same-origin policy
* `Location.hostname`
* `Location.host`
* `origin`


Document: preferredStyleSheetSet property - Web APIs

Document: preferredStyleSheetSet 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 **`preferredStyleSheetSet`** property returns the preferred style sheet set as set by the page
 author.

Value
-----

 The author's preferred style sheet set. This is determined from the order of style sheet declarations and the
 `Default-Style` HTTP header.

If there isn't a preferred style sheet set defined by the author, the empty string (`""`) is returned.

Examples
--------

```js
if (document.preferredStyleSheetSet) {
  console.log(
    `The preferred style sheet set is: ${document.preferredStyleSheetSet}`,
  );
} else {
  console.log("There is no preferred style sheet.");
}
```

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

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

See also
--------

* `document.lastStyleSheetSet`
* `document.selectedStyleSheetSet`
* `document.styleSheetSets`
* `document.enableStyleSheetsForSet()`


Document: plugins property - Web APIs

Document: plugins property
==========================

 The **`plugins`** read-only property of the
 `Document` interface returns an `HTMLCollection` object
 containing one or more `HTMLEmbedElement`s representing the
 `<embed>` elements in the current document.

**Note:** For a list of installed plugins, use Navigator.plugins
 instead.

Value
-----

An `HTMLCollection`.

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

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

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

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

See also
--------

* MSDN documentation


Document: activeElement property - Web APIs

Document: activeElement property
================================

 The **`activeElement`** read-only property
 of the `Document` interface returns the `Element` within the DOM that currently has focus.

 Often `activeElement` will return a `HTMLInputElement` or
 `HTMLTextAreaElement` object if it has the text selection at the time. If
 so, you can get more detail by using the object's `selectionStart` and `selectionEnd` properties.
 Other times the focused element might be a `<select>` element (menu) or
 an `<input>` element.

 Typically a user can press the tab key to move the focus around the page among
 focusable elements, and use the space bar to activate one (that is, to press a button or
 toggle a radio button). Which elements are focusable varies depending on the platform
 and the browser's current configuration. For example, on macOS systems, elements that
 aren't text input elements are not typically focusable by default.

**Note:** Focus (which element is receiving user input events) is not
 the same thing as selection (the currently highlighted part of the document). You can
 get the current selection using `window.getSelection()`.

Value
-----

 The `Element` which currently has focus, `<body>` or
 `null` if there is no focused element.

Examples
--------

### HTML

```html
<p>Select some text from one of the text areas below:</p>

<form>
  <textarea name="ta-example-one" id="ta-example-one" rows="7" cols="40">
This is Text Area One. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec tincidunt, lorem a porttitor molestie, odio nibh iaculis libero, et accumsan nunc orci eu dui.</textarea
 >
  <textarea name="ta-example-two" id="ta-example-two" rows="7" cols="40">
This is Text Area Two. Fusce ullamcorper, nisl ac porttitor adipiscing, urna orci egestas libero, ut accumsan orci lacus laoreet diam. Morbi sed euismod diam.</textarea
 >
</form>

<p>Active element ID: <em id="output-element"></em></p>
<p>Selected text: <em id="output-text"></em></p>
```

### JavaScript

```js
function onMouseUp(e) {
  const activeTextarea = document.activeElement;
  const selection = activeTextarea.value.substring(
    activeTextarea.selectionStart,
    activeTextarea.selectionEnd,
  );

  const outputElement = document.getElementById("output-element");
  const outputText = document.getElementById("output-text");
  outputElement.innerHTML = activeTextarea.id;
  outputText.innerHTML = selection;
}

const textarea1 = document.getElementById("ta-example-one");
const textarea2 = document.getElementById("ta-example-two");
textarea1.addEventListener("mouseup", onMouseUp, false);
textarea2.addEventListener("mouseup", onMouseUp, false);
```

### Result

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

| Specification |
| --- |
| HTML Standard # dom-documentorshadowroot-activeelement-dev |

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

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

See also
--------

* `Document.hasFocus`


Document: elementFromPoint() method - Web APIs

Document: elementFromPoint() method
===================================

 The **`elementFromPoint()`**
 method, available on the `Document` object, returns the topmost `Element` at the specified coordinates
 (relative to the viewport).

 If the element at the specified point belongs to another document (for example, the
 document of an `<iframe>`), that document's parent element is returned
 (the `<iframe>` itself). If the element at the given point is anonymous
 or XBL generated content, such as a textbox's scroll bars, then the first non-anonymous
 ancestor element (for example, the textbox) is returned.

 Elements with `pointer-events` set to `none` will be ignored,
 and the element below it will be returned.

 If the method is run on another document (like an `<iframe>`'s
 subdocument), the coordinates are relative to the document where the method is being
 called.

 If the specified point is outside the visible bounds of the document or either
 coordinate is negative, the result is `null`.

 If you need to find the specific position inside the element, use
 `Document.caretPositionFromPoint()`.

Syntax
------

```js
elementFromPoint(x, y)
```

### Parameters

`x`

 The horizontal coordinate of a point, relative to the left edge of the current
 viewport.

`y`

 The vertical coordinate of a point, relative to the top edge of the current
 viewport.

### Return value

The topmost `Element` object located at the specified coordinates.

Examples
--------

 This example creates two buttons which let you set the current color of the paragraph
 element located under the coordinates `(2, 2)`.

### JavaScript

```js
function changeColor(newColor) {
  elem = document.elementFromPoint(2, 2);
  elem.style.color = newColor;
}
```

 The `changeColor()` method obtains the element located at the specified
 point, then sets that element's current foreground `color` property to the
 color specified by the `newColor` parameter.

### HTML

```html
<p id="para1">Some text here</p>
<button onclick="changeColor('blue');">Blue</button>
<button onclick="changeColor('red');">Red</button>
```

 The HTML provides the paragraph whose color will be affected, as well as two buttons:
 one to change the color to blue, and another to change the color to red.

### Result

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

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

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

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

See also
--------

* `Document.elementsFromPoint()`


Document: URL property - Web APIs

Document: URL property
======================

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

Value
-----

A string containing the URL of the document.

Examples
--------

### JavaScript

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

### HTML

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

### Result

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

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

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

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

See also
--------

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


Document: exitPictureInPicture() method - Web APIs

Document: exitPictureInPicture() method
=======================================

 The **`exitPictureInPicture()`** method of the `Document` interface
 requests that a video contained
 in this document, which is currently floating, be taken out of picture-in-picture
 mode, restoring the previous state of the screen. This usually reverses the
 effects of a previous call to `HTMLVideoElement.requestPictureInPicture()`.

Syntax
------

```js
exitPictureInPicture()
```

### Parameters

None.

### Return value

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

### Exceptions

`InvalidStateError` `DOMException`

Thrown if `document.pictureInPictureElement` is `null`.

Examples
--------

 This example causes the current document to exit picture-in-picture mode whenever the
 mouse button is clicked within it.

```js
document.onclick = (event) => {
  if (document.pictureInPictureElement) {
    document
      .exitPictureInPicture()
      .then(() => console.log("Document Exited from Picture-in-Picture mode"))
      .catch((err) => console.error(err));
  } else {
    video.requestPictureInPicture();
  }
};
```

Note that if you want to track which video on your page is currently playing in picture-in-picture mode, you should listen to the `enterpictureinpicture` and `exitpictureinpicture` events on the `HTMLVideoElement` element(s) in question. Alternatively, you can check whether `Document.pictureInPictureElement` refers to the current `HTMLVideoElement` element.

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

| Specification |
| --- |
| Picture-in-Picture # ref-for-dom-document-exitpictureinpicture |

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.pictureInPictureElement`
* `:picture-in-picture`
* Picture-in-Picture events


Document: createComment() method - Web APIs

Document: createComment() method
================================

**`createComment()`** creates a new comment node, and returns
 it.

Syntax
------

```js
createComment(data)
```

### Parameters

`data`

A string containing the data to be added to the Comment.

### Return value

A new `Comment` object.

Examples
--------

```js
const docu = new DOMParser().parseFromString("<xml></xml>", "application/xml");
const comment = docu.createComment(
  "This is a not-so-secret comment in your document",
);

docu.querySelector("xml").appendChild(comment);

console.log(new XMLSerializer().serializeToString(docu));
// Displays: <xml><!--This is a not-so-secret comment in your document--></xml>
```

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

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

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

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


Document: createExpression() method - Web APIs

Document: createExpression() method
===================================

This method compiles an `XPathExpression` which can then be used for (repeated) evaluations.

You must call this method on the same document that you run the expression against.

Syntax
------

```js
createExpression(xpathText, namespaceURLMapper)
```

### Parameters

`xpathText`

A string which is the XPath expression to be compiled.

`namespaceURLMapper`

 A function which maps a namespace prefix to a
 namespace URL (or null if none needed).

### Return value

`XPathExpression`Examples
--------

```js
const xpathExpr = document.createExpression("//div");
const xpathResult = xpathExpr.evaluate(document); // returns an XPathResult object
const nodeContext = document.querySelector("nav");
// Re-using the XPathExpression "xpathExpr"
const otherResult = xpathExpr.evaluate(nodeContext); // returns an XPathResult object
```

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

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

See also
--------

* `Document.evaluate()`
* `XPathExpression`


Document: createTouch() method - Web APIs

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

**Note:** Use the `TouchEvent()` constructor.

Syntax
------

```js
createTouch(view, target, identifier, pageX, pageY, screenX, screenY)
```

### Parameters

**Note:** All parameters are optional.

`view`

The `window` in which the touch occurred.

`target`

The `EventTarget` for the touch.

`identifier`

The value for `Touch.identifier`.

`pageX`

The value for `Touch.pageX`.

`pageY`

The value for `Touch.pageY`.

`screenX`

The value for `Touch.screenX`.

`screenY`

The value for `Touch.screenY`.

**Note:** Previous versions of this method included the
 following additional parameters but those parameters are not included in either of the
 standards listed below. Consequently, these parameters should be considered deprecated
 and not used.

`clientX`

The value for `Touch.clientX`.

`clientY`

The value for `Touch.clientY`.

`radiusX`

The value for `Touch.radiusX`.

`radiusY`

The value for `Touch.radiusY`.

`rotationAngle`

The value for `Touch.rotationAngle`.

`force`

The value for `Touch.force`.

### Return value

`touch`

A `Touch` object configured as described by the input parameters.

Examples
--------

 This example illustrates using the `Document.createTouch()` method to
 create `Touch` objects.

 In following code snippet, two `Touch` objects are created for the
 `target` element.

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

const touch1 = document.createTouch(window, target, 1, 15, 20, 35, 40);
const touch2 = document.createTouch(window, target, 2, 25, 30, 45, 50);
```

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
* `TouchList`
* `Touch`
* `Document.createTouchList()`


Document: queryCommandEnabled() method - Web APIs

Document: queryCommandEnabled() 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.queryCommandEnabled()`** method reports whether
 or not the specified editor command is enabled by the browser.

Syntax
------

```js
document.queryCommandEnabled(command)
```

### Parameters

`command`

The command for which to determine support.

### Return value

 Returns a boolean value which is `true` if the command is enabled
 and `false` if the command isn't`.`

Notes
-----

* For '`cut`' and '`copy`' commands the method only returns true
 when called from a user-initiated thread.
* The `'paste'` command return `false` not only if the feature
 is unavailable, but also if the script calling it has insufficient privileges to
 perform the action.
Example
-------

```js
const flg = document.queryCommandEnabled("SelectAll");

if (flg) {
  document.execCommand("SelectAll", false, null); // command is enabled, run it
}
```

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

* `Document.execCommand()`
* `Document.queryCommandSupported()`


Document: links property - Web APIs

Document: links property
========================

The **`links`** read-only property of the `Document` interface returns a collection of all `<area>` elements and `<a>` elements in a document with a value for the href attribute.

Value
-----

An `HTMLCollection`.

Examples
--------

```js
for (const link of document.links) {
  const linkHref = document.createTextNode(link.href);
  const lineBreak = document.createElement("br");
  document.body.appendChild(linkHref);
  document.body.appendChild(lineBreak);
}
```

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

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

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

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


Document: referrer property - Web APIs

Document: referrer property
===========================

 The **`Document.referrer`** property returns the URI of the page that linked to
 this page.

Value
-----

 The value is an empty string if the user navigated to the page directly (not through a
 link, but, for example, by using a bookmark). Because this property returns only a
 string, it doesn't give you document object model (DOM) access to the referring page.

 Inside an `<iframe>`, the `Document.referrer` will initially
 be set to the same value as the `href` of
 the parent window's `Window.location`.

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

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

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

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


Document: title property - Web APIs

Document: title property
========================

 The **`document.title`** property gets or sets the current title of the document.
 When present, it defaults to the value of the `<title>`.

Value
-----

A string containing the *document*'s title. If the title was overridden by setting `document.title`, it contains that value. Otherwise, it contains the title specified in the `<title>` element.

```js
document.title = newTitle;
```

`newTitle` is the new title of the document. The assignment
 affects the return value of `document.title`, the title displayed for the
 document (e.g. in the titlebar of the window or tab), and it also affects the DOM of the
 document (e.g. the content of the `<title>` element in an HTML
 document).

Examples
--------

```html
<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" />
    <title>Hello World!</title>
  </head>
  <body>
    <script>
 alert(document.title); // displays "Hello World!"
 document.title = "Goodbye World!";
 alert(document.title); // displays "Goodbye World!"
 </script>
  </body>
</html>
```

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

| Specification |
| --- |
| HTML Standard # document.title |

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

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


Document: doctype property - Web APIs

Document: doctype property
==========================

 Returns the Document Type Declaration (DTD) associated with current document. The
 returned object implements the `DocumentType` interface. Use
 `DOMImplementation.createDocumentType()` to create a
 `DocumentType`.

* `doctype` is a read-only property.
Value
-----

A `DocumentType` object.

Examples
--------

```js
const doctypeObj = document.doctype;

console.log(`doctypeObj.name: ${doctypeObj.name}`);
console.log(`doctypeObj.internalSubset: ${doctypeObj.internalSubset}`);
console.log(`doctypeObj.publicId: ${doctypeObj.publicId}`);
console.log(`doctypeObj.systemId: ${doctypeObj.systemId}`);
```

Notes
-----

 The property returns `null` if there is no DTD associated with the current
 document.

DOM level 2 doesn't support editing the document type declaration.

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

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

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

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


Document: pointerlockchange event - Web APIs

Document: pointerlockchange event
=================================

The **`pointerlockchange`** event is fired when the pointer is locked/unlocked.

The event handler can use `Document.pointerLockElement` to determine whether the pointer is locked, and if so, to which element it is locked.

This event is not cancelable and does not bubble.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

Using `addEventListener()`:

```js
addEventListener("pointerlockchange", (event) => {
  if (document.pointerLockElement)
    console.log("The pointer is locked to: ", document.pointerLockElement);
  else {
    console.log("The pointer is not locked");
  }
});
```

Using the `onpointerlockchange` event handler property:

```js
document.onpointerlockchange = (event) => {
  if (document.pointerLockElement)
    console.log("The pointer is locked to: ", document.pointerLockElement);
  else {
    console.log("The pointer is not locked");
  }
};
```

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

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

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

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

See also
--------

* Using Pointer Lock API


Document: fragmentDirective property - Web APIs

Document: fragmentDirective property
====================================

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

The **`fragmentDirective`** read-only property of the `Document` interface returns the `FragmentDirective` for the current document.

Value
-----

A `FragmentDirective` object.

Examples
--------

Try running the following in a supporting browser's devtools, in a tab with one or more matched text fragments:

```js
document.fragmentDirective;
// returns an empty FragmentDirective object, if supported
// undefined otherwise
```

This functionality is mainly intended for feature detection at present. In the future, the `FragmentDirective` object could include additional information.

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

| Specification |
| --- |
| URL Fragment Text Directives # dom-document-fragmentdirective |

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

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

See also
--------

* Text fragments
* `::target-text`


Document: xmlVersion property - Web APIs

Document: xmlVersion 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 version number as specified in the XML declaration (e.g., `<?xml version="1.0"?>`) or "1.0" if the declaration is absent.

This attribute was never really useful, since it always returned 1.0, and has been removed in DOM Level 4. As such, Firefox 10 no longer implements it. Its primary use in the past was to detect whether or not the document was being rendered as XML rather than HTML. To detect this, you can create an element with its name in lower case, then check to see if it gets converted into all upper case (in which case the document is in the non-XML HTML mode):

```js
if (document.createElement("foo").tagName === "FOO") {
  /\* Document is not XML \*/
}
```

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: timeline property - Web APIs

Document: timeline property
===========================

Baseline 2022
-------------

Newly availableSince September 2022, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

* Learn more
* See full compatibility
* Report feedback
The `timeline` readonly property of the `Document` interface represents the default timeline of the current document. This timeline is a special instance of `DocumentTimeline`.

This timeline is unique to each `document` and persists for the lifetime of the `document` including calls to `Document.open()`.

 This timeline expresses the time in milliseconds since `Performance.timeOrigin`.
 Prior to the time origin, the timeline is inactive, and its `currentTime` is `null`.

**Note:** A document timeline that is associated with a non-active document (a `Document` not associated with a `Window`, `<iframe>`, or `<frame>`) is also considered to be inactive.

Value
-----

A `DocumentTimeline` object.

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

| Specification |
| --- |
| Web Animations # dom-document-timeline |

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

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

See also
--------

* Web Animations API
* `AnimationTimeline`
* `AnimationTimeline.currentTime`
* `DocumentTimeline`


Document: embeds property - Web APIs

Document: embeds property
=========================

 The **`embeds`** read-only property of the
 `Document` interface returns a list of the embedded
 `<embed>` elements within the current document.

Value
-----

An `HTMLCollection`.

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

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

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

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


Document: dir property - Web APIs

Document: dir property
======================

 The **`Document.dir`** property is a string
 representing the directionality of the text of the document, whether left to right
 (default) or right to left. Possible values are `'rtl'`, right to left, and
 `'ltr'`, left to right.

Value
-----

A string.

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

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

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

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

See also
--------

* `dir` global
 attribute


Document: lastStyleSheetSet property - Web APIs

Document: lastStyleSheetSet 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 **`Document.lastStyleSheetSet`** property returns the last enabled style sheet set. This property's
 value changes whenever the `document.selectedStyleSheetSet` property is
 changed.

Value
-----

The style sheet set that was most recently set. If the current style sheet set has not been changed by setting `document.selectedStyleSheetSet`, the returned value is `null`.

**Note:** This value doesn't change when
 `document.enableStyleSheetsForSet()` is called.

Examples
--------

```js
let lastSheetSet = document.lastStyleSheetSet;

if (!lastSheetSet) {
  lastSheetSet = "Style sheet not yet changed";
} else {
  console.log(`The last style sheet set is: ${lastSheetSet}`);
}
```

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

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

See also
--------

* `document.preferredStyleSheetSet`
* `document.selectedStyleSheetSet`
* `document.styleSheetSets`
* `document.enableStyleSheetsForSet()`


Document: cut event - Web APIs

Document: cut event
===================

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

The original target for this event is the `Element` that was the intended target of the cut 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: cut event.

Syntax
------

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

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

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

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

A `ClipboardEvent`. Inherits from `Event`.

Event

ClipboardEventExamples
--------

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

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

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

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

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

| Specification |
| --- |
| Clipboard API and events # clipboard-event-cut |
| HTML Standard # handler-oncut |

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

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

See also
--------

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


Document: anchors property - Web APIs

Document: anchors 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 **`anchors`** read-only property of the
 `Document` interface returns a list of all of the anchors in the document.

Value
-----

An `HTMLCollection`.

Examples
--------

```js
if (document.anchors.length >= 5) {
  dump("found too many anchors");
}
```

 The following is an example that auto populates a Table of Contents with every anchor
 on the page:

```html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Test</title>
    <script>
 function init() {
 const toc = document.getElementById("toc");
 for (const anchor of document.anchors) {
 const li = document.createElement("li");
 const newAnchor = document.createElement("a");
 newAnchor.href = "#" + anchor.name;
 newAnchor.textContent = anchor.text;
 li.appendChild(newAnchor);
 toc.appendChild(li);
 }
 }
 </script>
  </head>
  <body onload="init()">
    <h1>Title</h1>
    <h2><a name="contents">Contents</a></h2>
    <ul id="toc"></ul>

    <h2><a name="plants">Plants</a></h2>
    <ol>
      <li>Apples</li>
      <li>Oranges</li>
      <li>Pears</li>
    </ol>

    <h2><a name="veggies">Veggies</a></h2>
    <ol>
      <li>Carrots</li>
      <li>Celery</li>
      <li>Beats</li>
    </ol>
  </body>
</html>
```

View on JSFiddle

Notes
-----

 For reasons of backwards compatibility, the returned set of anchors only contains those
 anchors created with the `name` attribute, not those created with the
 `id` attribute.

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

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

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

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


Document: currentScript property - Web APIs

Document: currentScript property
================================

The **`Document.currentScript`** property returns the `<script>` element whose script is currently being processed and isn't a JavaScript module. (For modules use `import.meta` instead.)

 It's important to note that this will not reference the `<script>`
 element if the code in the script is being called as a callback or event handler; it
 will only reference the element while it's initially being processed.

Value
-----

A `HTMLScriptElement` or null.

Examples
--------

This example checks to see if the script is being executed asynchronously:

```js
if (document.currentScript.async) {
  console.log("Executing asynchronously");
} else {
  console.log("Executing synchronously");
}
```

View Live Examples

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

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

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

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

See also
--------

* `import.meta`
* `<script>`
* `document.afterscriptexecute_event`
* `document.beforescriptexecute_event`


Document: createAttributeNS() method - Web APIs

Document: createAttributeNS() method
====================================

 The **`Document.createAttributeNS()`** method creates a new attribute node
 with the specified namespace URI and qualified name, 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.

Syntax
------

```js
createAttributeNS(namespaceURI, qualifiedName)
```

### Parameters

`namespaceURI`

 A string that specifies the namespace URI to associate with the attribute.
 The `namespaceURI` property of the created attribute is initialized with the value of `namespaceURI`.
 See Valid Namespace URIs.

`qualifiedName`

 A string that specifies the name of attribute to be created.
 The `name` property of the created attribute is initialized with the value of `qualifiedName`.

### Return value

The new `Attr` node.

### Exceptions

`NamespaceError` `DOMException`

Thrown if the `namespaceURI` value is not a valid namespace URI.

`InvalidCharacterError` `DOMException`

Thrown if the `qualifiedName` 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.

Important Namespace URIs
------------------------

HTML

`http://www.w3.org/1999/xhtml`

SVG

`http://www.w3.org/2000/svg`

MathML

`http://www.w3.org/1998/Math/MathML`

Examples
--------

```js
const node = document.getElementById("svg");
const a = document.createAttributeNS("http://www.w3.org/2000/svg", "viewBox");
a.value = "0 0 100 100";
node.setAttributeNode(a);
console.log(node.getAttribute("viewBox")); // "0 0 100 100"
```

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

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

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

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

See also
--------

* `Document.createAttribute()`
* `Document.createElementNS()`
* `Element.setAttributeNS()`
* `Element.setAttributeNode()`
* `Element.setAttributeNodeNS()`


Document: selectedStyleSheetSet property - Web APIs

Document: selectedStyleSheetSet 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 **`selectedStyleSheetSet`** property indicates the name of the style sheet set that's currently in use.

Value
-----

The name of the style sheet set currently in use. You can also set the current style sheet set using this property.

 Setting the value of this property is equivalent to calling
 `document.enableStyleSheetsForSet()` with the value of
 `currentStyleSheetSet`, then setting the value of
 `lastStyleSheetSet` to that value as well.

**Note:** This attribute's value is live; directly changing
 the `disabled` attribute on style sheets will affect the value of this
 attribute.

Examples
--------

```js
console.log(`Current style sheet set: ${document.selectedStyleSheetSet}`);

document.selectedStyleSheetSet = "Some other style sheet";
```

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

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

See also
--------

* `document.lastStyleSheetSet`
* `document.preferredStyleSheetSet`
* `document.styleSheetSets`
* `document.enableStyleSheetsForSet()`


Document: children property - Web APIs

Document: children property
===========================

 The read-only **`children`** property returns a live `HTMLCollection`
 which contains all of the child `elements` of the document upon which it was called.

For HTML documents, this is usually only the root `<html>` element.

See `Element.children` for child elements of specific HTML elements within the document.

Value
-----

 An `HTMLCollection` which is a live, ordered collection of the DOM
 elements which are children of the current document. You can access the
 individual child nodes in the collection by using either the
 `item()` method on the collection, or by using
 JavaScript array-style notation.

 If the document has no element children, then `children` is an empty list with a
 `length` of `0`.

Examples
--------

```js
document.children;
// HTMLCollection [<html>]
// Usually only contains the root <html> element, the document's only direct child
```

See `Element.children` for child elements of specific HTML elements within the document.

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

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

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

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

See also
--------

* `Element.children`
* `Node.childNodes`


Document: vlinkColor property - Web APIs

Document: vlinkColor 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 **`Document.vlinkColor`** property gets/sets the color of
 links that the user has visited in the document.

Value
-----

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

Notes
-----

* The default value for this property in Mozilla Firefox is purple
 (`#551a8b` in hexadecimal).
* `Document.vlinkColor` is deprecated in DOM Level 2 HTML.
* The recommended alternative is to get/set the color of the CSS `:visited` pseudo-class on HTML `<a>` elements (e.g.,
 `a:visited {color:red;}`).
* Another alternative is `document.body.vLink`, although this is 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: firstElementChild property - Web APIs

Document: firstElementChild property
====================================

 The **`Document.firstElementChild`** read-only property
 returns the document's first child `Element`, or `null` if there
 are no child elements.

For HTML documents, this is usually the only child, the root `<html>` element.

See `Element.firstElementChild` for the first child element of specific elements within a document.

Value
-----

A `Element` object, or `null`.

Examples
--------

```js
document.firstElementChild;
// returns the root <html> element, the only child of the document
```

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

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

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

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

See also
--------

* `Element.firstElementChild`


Document: createNodeIterator() method - Web APIs

Document: createNodeIterator() method
=====================================

The **`Document.createNodeIterator()`** method returns a new `NodeIterator` object.

Syntax
------

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

### Parameters

`root`

The root node at which to begin the `NodeIterator`'s traversal.

`whatToShow` Optional

 An optional `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 `SHOW_ALL` constant.

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

`filter` Optional

A callback function or an object with an `acceptNode()` method. 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. The method should return one of `NodeFilter.FILTER_ACCEPT`, `NodeFilter.FILTER_REJECT`, or `NodeFilter.FILTER_SKIP`. See the Example.

### Return value

A new `NodeIterator` object.

Examples
--------

```js
const nodeIterator = document.createNodeIterator(
  document.body,
  NodeFilter.SHOW\_ELEMENT,
  (node) =>
    node.nodeName.toLowerCase() === "p"
      ? NodeFilter.FILTER\_ACCEPT
      : NodeFilter.FILTER\_REJECT,
);
const pars = [];
let currentNode;

while ((currentNode = nodeIterator.nextNode())) {
  pars.push(currentNode);
}
```

The same, but using an object with an `acceptNode()` method:

```js
const nodeIterator = document.createNodeIterator(
  document.body,
  NodeFilter.SHOW\_ELEMENT,
  {
    acceptNode(node) {
      return node.nodeName.toLowerCase() === "p"
        ? NodeFilter.FILTER\_ACCEPT
        : NodeFilter.FILTER\_REJECT;
    },
  },
);
const pars = [];
let currentNode;

while ((currentNode = nodeIterator.nextNode())) {
  pars.push(currentNode);
}
```

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

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

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

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


Document: lastElementChild property - Web APIs

Document: lastElementChild property
===================================

 The **`Document.lastElementChild`** read-only property
 returns the document's last child `Element`, or `null` if there
 are no child elements.

For HTML documents, this is usually the only child, the root `<html>` element.

See `Element.lastElementChild` for the last child element of specific elements within a document.

Value
-----

The root `<html>` element.

Examples
--------

```js
document.lastElementChild;
// returns the root <html> element, the only child of the document
```

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

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

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

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

See also
--------

* `Element.lastElementChild`


Document: documentElement property - Web APIs

Document: documentElement property
==================================

**`Document.documentElement`** returns the
 `Element` that is the root element of the `document` (for
 example, the `<html>` element for HTML documents).

Value
-----

A `Element` object.

Examples
--------

```js
const rootElement = document.documentElement;
const firstTier = rootElement.childNodes;
// firstTier is a NodeList of the direct children of the root element
// such as <head> and <body>

for (const child of firstTier) {
  // do something with each direct child of the root element
}
```

Notes
-----

 For any non-empty HTML document, `documentElement` will always be an
 `<html>` element. For any non-empty XML document,
 `documentElement` will always be whatever element is the root element of the
 document.

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

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

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

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


Document: writeln() method - Web APIs

Document: writeln() method
==========================

**Warning:** Use of the `document.writeln()` method is strongly discouraged.

As the HTML spec itself warns:

>
>
>  This method has very idiosyncratic behavior. In some cases, this method can affect the state of the HTML parser while the parser is running, resulting in a DOM that does not correspond to the source of the document (e.g. if the string written is the string "`<plaintext>`" or "`<!--`"). In other cases, the call can clear the current page first, as if `document.open()` had been called. In yet more cases, the method is simply ignored, or throws an exception. Users agents are explicitly allowed to avoid executing `script` elements inserted via this method. And to make matters even worse, the exact behavior of this method can in some cases be dependent on network latency, which can lead to failures that are very hard to debug. For all these reasons, use of this method is strongly discouraged.
>  Therefore, avoid using `document.writeln()` — and if possible, update any existing code that is still using it.
>
>
>
>

Writes a string of text followed by a newline character to a document.

Syntax
------

```js
writeln(line)
```

### Parameters

* `line` is string containing a line of text.
### Return value

None (`undefined`).

Examples
--------

```js
document.writeln("<p>enter password:</p>");
```

Notes
-----

**document.writeln** is the same as `document.write` but adds a newline.

**Note:** **document.writeln** (like **document.write**) does not work in XHTML documents (you'll get a "Operation is not supported" (`NS_ERROR_DOM_NOT_SUPPORTED_ERR`) error on the error console). This is the case if opening a local file with a .xhtml file extension or for any document served with an application/xhtml+xml MIME type. More information is available in the W3C XHTML FAQ.

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

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

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

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


Document: scroll event - Web APIs

Document: scroll event
======================

 The **`scroll`** event fires when the document view has been scrolled.
 To detect when scrolling has completed, see the `Document: scrollend event`.
 For element scrolling, see `Element: scroll event`.

Syntax
------

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

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

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

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

A generic `Event`.

Examples
--------

### Scroll event throttling

Since `scroll` events can fire at a high rate, the event handler shouldn't execute computationally expensive operations such as DOM modifications. Instead, it is recommended to throttle the event using `requestAnimationFrame()`, `setTimeout()`, or a `CustomEvent`, as follows.

Note, however, that input events and animation frames are fired at about the same rate, and therefore the optimization below is often unnecessary. This example optimizes the `scroll` event for `requestAnimationFrame`.

```js
let lastKnownScrollPosition = 0;
let ticking = false;

function doSomething(scrollPos) {
  // Do something with the scroll position
}

document.addEventListener("scroll", (event) => {
  lastKnownScrollPosition = window.scrollY;

  if (!ticking) {
    window.requestAnimationFrame(() => {
      doSomething(lastKnownScrollPosition);
      ticking = false;
    });

    ticking = true;
  }
});
```

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

| Specification |
| --- |
| CSSOM View Module # eventdef-document-scroll |
| HTML Standard # handler-onscroll |

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

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

See also
--------

* Document: `scrollend` event
* Element: `scroll` event
* Element: `scrollend` event


Document: fullscreen property - Web APIs

Document: fullscreen 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 obsolete `Document` interface's **`fullscreen`** read-only property reports whether or not the document is currently displaying content in fullscreen mode.

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.

**Note:** Since this property is deprecated, you can determine if fullscreen mode is active on the document by checking to see if `Document.fullscreenElement` is not `null`.

Value
-----

A Boolean value which is `true` if the document is currently displaying an element in fullscreen mode; otherwise, the value is `false`.

Examples
--------

This simple function reports whether or not fullscreen mode is currently active, using the obsolete `fullscreen` property.

```js
function isDocumentInFullScreenMode() {
  return document.fullscreen;
}
```

This next example, on the other hand, uses the current `fullscreenElement` property to determine the same thing:

```js
function isDocumentInFullScreenMode() {
  return document.fullscreenElement !== null;
}
```

If `fullscreenElement` isn't `null`, this returns `true`, indicating that fullscreen mode is in effect.

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

| Specification |
| --- |
| Fullscreen API Standard # dom-document-fullscreen |

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
* `Document.fullscreenEnabled`


Document: characterSet property - Web APIs

Document: characterSet property
===============================

 The **`Document.characterSet`**
 read-only property returns the character encoding of the
 document that it's currently rendered with.

**Note:** A "character set" and a "character encoding" are related, but different. Despite the
 name of this property, it returns the *encoding*.

 Users can override the developer-specified encoding inside the Content-Type header or inline
 like `<meta charset="utf-8">`, such as with Firefox's `View → Text
Encoding` menu. This override is provided to fix incorrect developer-specified
 encodings that result in garbled text.

**Note:** The properties `document.charset` and `document.inputEncoding`
 are legacy aliases for `document.characterSet`. Do not use them any more.

Value
-----

A string.

Examples
--------

```html
<button onclick="console.log(document.characterSet);">
  Log character encoding
</button>
<!-- displays document's character encoding in the dev console, such as "ISO-8859-1" or "UTF-8" -->
```

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

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

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

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


Document: createCDATASection() method - Web APIs

Document: createCDATASection() method
=====================================

**`createCDATASection()`** creates a new CDATA section node,
 and returns it.

Syntax
------

```js
createCDATASection(data)
```

### Parameters

`data`

A string containing the data to be added to the CDATA Section.

### Return value

A CDATA Section node.

Examples
--------

```js
const docu = new DOMParser().parseFromString("<xml></xml>", "application/xml");
const cdata = docu.createCDATASection("Some <CDATA> data & then some");
docu.querySelector("xml").appendChild(cdata);
console.log(new XMLSerializer().serializeToString(docu));
// Displays: <xml><![CDATA[Some <CDATA> data & then some]]></xml>
```

Notes
-----

* This will only work with XML, not HTML documents (as HTML documents do not support
 CDATA sections); attempting it on an HTML document will throw
 `NOT_SUPPORTED_ERR`.
* Will throw a `NS_ERROR_DOM_INVALID_CHARACTER_ERR` exception if one tries
 to submit the closing CDATA sequence ("`]]>`") as part of the data, so
 unescaped user-provided data cannot be safely used without this method getting this
 exception (`createTextNode()` can often be used
 in its place).
Specifications
--------------

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

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

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