recursal/MDN huggingface dataset:
Document: createNSResolver() method
===================================

Creates an `XPathNSResolver` which resolves namespaces with respect to the definitions in scope for a specified node.

Syntax
------


```js
createNSResolver(node)
```

### Parameters

* `node` is the node to be used as a context for namespace resolution.
### Return value

* `nsResolver` is an XPathNSResolver object.
Notes
-----

Adapts any DOM node to resolve namespaces so that an XPath expression can be easily evaluated relative to the context of the node where it appeared within the document. This adapter works like the DOM Level 3 method `lookupNamespaceURI` on nodes in resolving the `namespaceURI` from a given prefix using the current information available in the node's hierarchy at the time `lookupNamespaceURI` is called. Also correctly resolves the implicit `xml` prefix.

Note, XPath defines QNames without prefix to match only elements in the null namespace. There is no way in XPath to pick up the default namespace as applied to a regular element reference (e.g., `p[@id='_myid'`] for `xmlns='http://www.w3.org/1999/xhtml'`). To match default elements in a non-null namespace, you either have to refer to a particular element using a form such as `*namespace-uri()=http://www.w3.org/1999/xhtml and name()=p[@id='_myid']` (this approach works well for dynamic XPath expressions where the namespaces might not be known) or use prefixed name tests, and create a namespace resolver mapping the prefix to the namespace. Read more on how to create a user defined namespace resolver if you wish to take the latter approach.

`createNSResolver` was introduced in DOM Level 3.

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

| Specification |
| --- |
| DOM Standard # dom-xpathevaluatorbase-creatensresolver |

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

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

See also
--------

* document.evaluate
* Introduction to using XPath in JavaScript
Document: hasFocus() method
===========================

 The **`hasFocus()`** method of the `Document` interface returns a boolean value indicating whether the document or any element inside the document has focus.
 This method can be used to determine whether the active element in a document has focus.


**Note:** When viewing a document, an element with focus is always the active element in the document, but an active element does not necessarily have focus.
 For example, an active element within a popup window that is not the foreground doesn't have focus.


Syntax
------


```js
hasFocus()
```

### Parameters

None.

### Return value

`false` if the active element in the document has no focus;
 `true` if the active element in the document has focus.

Examples
--------

 The following example checks whether the document has focus or not.
 A function called `checkPageFocus()` updates a paragraph element depending on the result of `document.hasFocus()`.
 Opening a new window will cause the document to lose focus and switching back to the original window will cause the document to regain focus.

### HTML


```html
<p id="log">Focus check results are shown here.</p>
<button id="newWindow">Open new window</button>
```


```
body {
  padding: 1rem;
  background: gray;
  text-align: center;
  font-size: 1.5rem;
}
```

### JavaScript


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

function checkDocumentFocus() {
  if (document.hasFocus()) {
    log.textContent = "This document has focus.";
    body.style.background = "white";
  } else {
    log.textContent = "This document does not have focus.";
    body.style.background = "gray";
  }
}

function openWindow() {
  window.open(
    "https://developer.mozilla.org/",
    "MDN",
    "width=640,height=320,left=150,top=150",
  );
}

document.getElementById("newWindow").addEventListener("click", openWindow);
setInterval(checkDocumentFocus, 300);
```

### Result

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

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

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

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

See also
--------

* `Document.activeElement`
* Using the Page Visibility API
Document: queryCommandSupported() 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.queryCommandSupported()`** method reports
 whether or not the specified editor command is supported by the browser.

Syntax
------


```js
queryCommandSupported(command)
```

### Parameters

`command`

The command for which to determine support.

### Return value

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

Notes
-----

 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.

Examples
--------


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

if (flg) {
  // Do something…
}
```

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.queryCommandEnabled()`
Document: prerendering property
===============================

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

The **`prerendering`** read-only property of the `Document` interface returns `true` if the document is currently in the process of prerendering, as initiated via the Speculation Rules API.

Value
-----

A boolean. Returns `true` if the document is currently in the process of prerendering, and `false` if it is not. `false` will be returned for documents that have finished prerendering, and documents that were not prerendered.

Examples
--------

To run an activity while the page is prerendering, you can check for the `prerendering` property. You could for example run some analytics:


```js
if (document.prerendering) {
  analytics.sendInfo("got this far during prerendering!");
}
```


When a prerendered document is activated, `PerformanceNavigationTiming.activationStart` is set to a `DOMHighResTimeStamp` value representing the time between when the prerender was started and the document was actually activated. The following function can check for prerendering *and* prerendered pages:


```js
function pagePrerendered() {
  return (
    document.prerendering ||
    self.performance?.getEntriesByType?.("navigation")[0]?.activationStart > 0
  );
}
```


When the prerendered page is activated by the user viewing the page, the `prerenderingchange` event will fire. This can be used to enable activities that previously would be started by default on page load but which you wish to delay until the page is actually viewed by the user. The following code sets up an event listener to run a function once prerendering has finished, on a prerendered page, or runs it immediately on a non-prerendered page:


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


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

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

| Specification |
| --- |
| Prerendering Revamped # dom-document-prerendering |

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

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

See also
--------

* Speculation Rules API
* `prerenderingchange` event
Document: open() method
=======================

 The **`Document.open()`** method opens a document for
 writing.

This does come with some side effects. For example:

* All event listeners currently registered on the document, nodes inside the document,
 or the document's window are removed.
* All existing nodes are removed from the document.
Syntax
------


```js
open()
```

### Parameters

None.

### Return value

A `Document` object instance.

Examples
--------

 The following simple code opens the document and replaces its content with a number of
 different HTML fragments, before closing it again.


```js
document.open();
document.write("<p>Hello world!</p>");
document.write("<p>I am a fish</p>");
document.write("<p>The number is 42</p>");
document.close();
```

Notes
-----

 An automatic `document.open()` call happens when
 `document.write()` is called after the page has loaded.

### Content Security

This method is subject to the same same-origin policy as other properties, and does not work if doing so would change the document's origin.

Three-argument document.open()
------------------------------

 There is a lesser-known and little-used three-argument version of
 `document.open()`, which is an alias of `Window.open()` (see
 its page for full details).

 This call, for example opens github.com in a new window, with its opener set to
 `null`:


```js
document.open("https://www.github.com", "", "noopener=true");
```

Two-argument document.open()
----------------------------

 Browsers used to support a two-argument `document.open()`, with the
 following signature:


```js
document.open(type, replace);
```


 Where `type` specified the MIME type of the data you are writing (e.g.
 `text/html`) and replace if set (i.e. a string of `"replace"`)
 specified that the history entry for the new document would replace the current history
 entry of the document being written to.

 This form is now obsolete; it won't throw an error, but instead just forwards to
 `document.open()` (i.e. is the equivalent of just running it with no
 arguments). The history-replacement behavior now always happens.

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

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

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

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

See also
--------

* `Document`
* `Window.open()`
Document: createDocumentFragment() method
=========================================

 Creates a new empty `DocumentFragment` into which
 DOM nodes can be added to build an offscreen DOM tree.

Syntax
------


```js
createDocumentFragment()
```

### Parameters

None.

### Return value

 A newly created, empty, `DocumentFragment` object, which is ready to have
 nodes inserted into it.

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

`DocumentFragment`s are DOM `Node` objects which are never part
 of the main DOM tree. The usual use case is to create the document fragment, append
 elements to the document fragment and then append the document fragment to the DOM tree.
 In the DOM tree, the document fragment is replaced by all its children.

 Since the document fragment is *in memory* and not part of the main DOM tree,
 using document fragments could result in better performance
 in some older engines.

 You can also use the `DocumentFragment` constructor to create a new
 fragment:


```js
const fragment = new DocumentFragment();
```

Examples
--------

 This example creates a list of major web browsers in a `DocumentFragment`,
 then adds the new DOM subtree to the document to be displayed.

### HTML


```html
<ul id="ul"></ul>
```

### JavaScript


```js
const element = document.getElementById("ul"); // assuming ul exists
const fragment = document.createDocumentFragment();
const browsers = ["Firefox", "Chrome", "Opera", "Safari"];

browsers.forEach((browser) => {
  const li = document.createElement("li");
  li.textContent = browser;
  fragment.appendChild(li);
});

element.appendChild(fragment);
```

### Result

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

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

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

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

See also
--------

* `document.implementation.createDocument()`
* `documentFragment`
IDBTransaction: commit() method
===============================

The **`commit()`** method of the `IDBTransaction` interface commits the transaction if it is called on an active transaction.

Note that `commit()` doesn't normally *have* to be called — a transaction will automatically commit when all outstanding requests have been satisfied and no new requests have been made. `commit()` can be used to start the commit process without waiting for events from outstanding requests to be dispatched.

If it is called on a transaction that is not active, it throws an `InvalidStateError` `DOMException`.

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

Syntax
------


```js
commit()
```

### Parameters

None.

### Return value

None (`undefined`).

### Exceptions

`InvalidStateError` `DOMException`

Thrown if the transaction state is not active.

Examples
--------


```js
const note = document.getElementById("notifications");

// open a read/write db transaction, ready for adding the data
const transaction = db.transaction(["myDB"], "readwrite");

// report on the success of opening the transaction
transaction.oncomplete = (event) => {
  note.innerHTML +=
    "<li>Transaction completed: database modification finished.</li>";
};

transaction.onerror = (event) => {
  note.innerHTML +=
    "<li>Transaction not opened due to error. Duplicate items not allowed.</li>";
};

// create an object store on the transaction
const objectStore = transaction.objectStore("myObjStore");

// add our newItem object to the object store
const objectStoreRequest = objectStore.add(newItem[0]);

objectStoreRequest.onsuccess = (event) => {
  // report the success of the request (this does not mean the item
  // has been stored successfully in the DB - for that you need transaction.onsuccess)
  note.innerHTML += "<li>Request successful.</li>";
};

// Force the changes to be committed to the database asap
transaction.commit();
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbtransaction-commit② |

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

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

See also
--------

* Using IndexedDB
* Starting transactions: `IDBDatabase`
* Using transactions: `IDBTransaction`
* Setting a range of keys: `IDBKeyRange`
* Retrieving and making changes to your data: `IDBObjectStore`
* Using cursors: `IDBCursor`
* Reference example: To-do Notifications (View the example live).
IDBTransaction: objectStoreNames property
=========================================

 The **`objectStoreNames`** read-only property of the
 `IDBTransaction` interface returns a `DOMStringList` of names
 of `IDBObjectStore` objects.

Value
-----

A `DOMStringList` of names of `IDBObjectStore` objects.

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbtransaction-objectstorenames① |

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

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

See also
--------

* Using IndexedDB
* Starting transactions: `IDBDatabase`
* Using transactions: `IDBTransaction`
* Setting a range of keys: `IDBKeyRange`
* Retrieving and making changes to your data: `IDBObjectStore`
* Using cursors: `IDBCursor`
* Reference example: To-do Notifications (View the example live).
IDBTransaction: durability property
===================================

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

 The **`durability`** read-only property of the
 `IDBTransaction` interface returns the durability hint the transaction was
 created with. This is a hint to the user agent of whether to prioritize performance or
 durability when committing the transaction.

The value of this property is defined in the `options` parameter when creating a transaction using `IDBDatabase.transaction()`.

Value
-----

Any of the following literal `strings`:

`"strict"`

 The user agent may consider that the transaction has
 successfully committed only after verifying that all outstanding changes have been
 successfully written to a persistent storage medium.


`"relaxed"`

 The user agent may consider that the transaction has
 successfully committed as soon as all outstanding changes have been written to the
 operating system, without subsequent verification.


`"default"`

 The user agent should use its default durability behavior
 for the storage bucket. This is the default for transactions if not otherwise
 specified.


Examples
--------

For a full working example, see our To-do Notifications app (view example live).

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

| Specification |
| --- |
| Indexed Database API 3.0 # dom-idbtransaction-durability |

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

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

 The **`db`** read-only property of the `IDBTransaction` interface returns the database connection
 with which this transaction is associated.

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

Value
-----

An `IDBDatabase` object.

Examples
--------

 In the following code snippet, we open a read/write transaction on our database and add
 some data to an object store. Note also the functions attached to transaction event
 handlers to report on the outcome of the transaction opening in the event of success or
 failure. At the end, we return the associated database connection using `db`.
 For a full working example, see our To-do Notifications app (view example live).


```js
const note = document.getElementById("notifications");

// an instance of a db object for us to store the IDB data in
let db;

// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

DBOpenRequest.onsuccess = (event) => {
  note.innerHTML += "<li>Database initialized.</li>";

  // store the result of opening the database in the db variable.
  // This is used a lot below
  db = DBOpenRequest.result;

  // Run the addData() function to add the data to the database
  addData();
};

function addData() {
  // Create a new object ready for being inserted into the IDB
  const newItem = [
    {
      taskTitle: "Walk dog",
      hours: 19,
      minutes: 30,
      day: 24,
      month: "December",
      year: 2013,
      notified: "no",
    },
  ];

  // open a read/write db transaction, ready for adding the data
  const transaction = db.transaction(["toDoList"], "readwrite");

  // report on the success of opening the transaction
  transaction.oncomplete = (event) => {
    note.innerHTML +=
      "<li>Transaction completed: database modification finished.</li>";
  };

  transaction.onerror = (event) => {
    note.innerHTML +=
      "<li>Transaction not opened due to error. Duplicate items not allowed.</li>";
  };

  // create an object store on the transaction
  const objectStore = transaction.objectStore("toDoList");

  // add our newItem object to the object store
  const objectStoreRequest = objectStore.add(newItem[0]);

  objectStoreRequest.onsuccess = (event) => {
    // report the success of the request (this does not mean the item
    // has been stored successfully in the DB - for that you need transaction.onsuccess)
    note.innerHTML += "<li>Request successful.</li>";
  };

  // Return the database (IDBDatabase) connection with which this transaction is associated
  transaction.db;
}
```

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

| Specification |
| --- |
| Indexed Database API 3.0 # ref-for-dom-idbtransaction-db① |

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

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

See also
--------

* Using IndexedDB
* Starting transactions: `IDBDatabase`
* Using transactions: `IDBTransaction`
* Setting a range of keys: `IDBKeyRange`
* Retrieving and making changes to your data: `IDBObjectStore`
* Using cursors: `IDBCursor`
* Reference example: To-do Notifications (View the example live).
FileSystemHandle: requestPermission() method
============================================

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

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

 The **`requestPermission()`** method of the
 `FileSystemHandle` interface requests read or readwrite permissions for the
 file handle.

Syntax
------


```js
requestPermission(fileSystemHandlePermissionDescriptor)
```

### Parameters

FileSystemHandlePermissionDescriptor Optional

An object which specifies the permission mode to query for. Options are as follows:

* `'mode'`: Can be either `'read'` or
 `'readwrite'`.

### Return value

A `Promise` that resolves to a `PermissionStatus` object.

### Exceptions

`TypeError`

 Thrown if no parameter is specified or the `mode` is not that of
 `'read'` or `'readwrite'`

Examples
--------

The following asynchronous function requests permissions if they have not been granted.


```js
// fileHandle is a FileSystemFileHandle
// withWrite is a boolean set to true if write

async function verifyPermission(fileHandle, withWrite) {
  const opts = {};
  if (withWrite) {
    opts.mode = "readwrite";
  }

  // Check if we already have permission, if so, return true.
  if ((await fileHandle.queryPermission(opts)) === "granted") {
    return true;
  }

  // Request permission to the file, if the user grants permission, return true.
  if ((await fileHandle.requestPermission(opts)) === "granted") {
    return true;
  }

  // The user did not grant permission, return false.
  return false;
}
```

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

| Specification |
| --- |
| File System Access # api-filesystemhandle-requestpermission |

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

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

See also
--------

* File System API
* The File System Access API: simplifying access to local files
FileSystemHandle: name property
===============================

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

 The **`name`** read-only property of the
 `FileSystemHandle` interface returns the name of the entry represented by
 handle.

Value
-----

A string.

Examples
--------

 The following function allows the user to choose a file from the file picker and
 retrieve the `name` property.


```js
// store a reference to our file handle
let fileHandle;

async function getFile() {
  // open file picker
  [fileHandle] = await window.showOpenFilePicker();

  const fileName = fileHandle.name;
}
```

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

| Specification |
| --- |
| File System Standard # ref-for-dom-filesystemhandle-name① |

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

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

See also
--------

* File System API
* The File System Access API: simplifying access to local files