recursal/MDN huggingface dataset:
Locating DOM elements using selectors
=====================================

The Selectors API provides methods that make it quick and easy to retrieve `Element` nodes from the DOM by matching against a set of selectors. This is much faster than past techniques, wherein it was necessary to, for example, use a loop in JavaScript code to locate the specific items you needed to find.

The NodeSelector interface
--------------------------

This specification adds two new methods to any objects implementing the `Document`, `DocumentFragment`, or `Element` interfaces:

`querySelector()`

Returns the first matching `Element` node within the node's subtree. If no matching node is found, `null` is returned.

`querySelectorAll()`

Returns a `NodeList` containing all matching `Element` nodes within the node's subtree, or an empty `NodeList` if no matches are found.


**Note:** The `NodeList` returned by `querySelectorAll()` is not live, which means that changes in the DOM are not reflected in the collection. This is different from other DOM querying methods that return live node lists.

You may find examples and details by reading the documentation for the `Element.querySelector()` and `Element.querySelectorAll()` methods.

Selectors
---------

The selector methods accept selectors to determine what element or elements should be returned. This includes selector lists so you can group multiple selectors in a single query.

To protect the user's privacy, some pseudo-classes are not supported or behave differently. For example `:visited` will return no matches and `:link` is treated as `:any-link`.

Only elements can be selected, so pseudo-classes are not supported.

Examples
--------

To select all paragraph (`p`) elements in a document whose classes include `warning` or `note`, you can do the following:


```js
const special = document.querySelectorAll("p.warning, p.note");
```


You can also query by ID. For example:


```js
const el = document.querySelector("#main, #basic, #exclamation");
```


After executing the above code, `el` contains the first element in the document whose ID is one of `main`, `basic`, or `exclamation`.

See also
--------

* Selectors specification
* CSS Selectors
* `Element.querySelector()`
* `Element.querySelectorAll()`
* `Document.querySelector()`
* `Document.querySelectorAll()`
Example
=======


```html
<html>
  <head>
    <title>My Document</title>
    <script>
 function change() {
 // document.getElementsByTagName("H1") returns a NodeList of the h1
 // elements in the document, and the first is number 0:
 const header = document.getElementsByTagName("H1").item(0);
 // the firstChild of the header is a Text node:
 header.firstChild.data = "A dynamic document";
 // now the header is "A dynamic document".
 const para = document.getElementsByTagName("P").item(0);
 para.firstChild.data = "This is the first paragraph.";
 // create a new Text node for the second paragraph
 const newText = document.createTextNode(
 "This is the second paragraph.",
 );
 // create a new Element to be the second paragraph
 const newElement = document.createElement("P");
 // put the text in the paragraph
 newElement.appendChild(newText);
 // and put the paragraph on the end of the document by appending it to
 // the BODY (which is the parent of para)
 para.parentNode.appendChild(newElement);
 }
 </script>
  </head>
  <body>
    <input type="button" value="Change this document." onclick="change()" />
    <h1>Header</h1>
    <p>Paragraph</p>
  </body>
</html>
```
XRSessionEvent: XRSessionEvent() constructor
============================================

 The WebXR Device API's
 **`XRSessionEvent()`** constructor creates and returns a new
 `XRSessionEvent` object. These objects represent events announcing
 state changes in an `XRSession` representing an augmented or virtual
 reality session.

Syntax
------


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

### Parameters

`type`

 A string with the name of the event.
 It is case-sensitive and browsers set it to `end` or `visibilitychange`.


`options`

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

`session`

The `XRSession` to which the event is to be delivered.


### Return value

 A new `XRSessionEvent` object representing an object of the
 specified type and configured as described by the `options` parameter.

Examples
--------

See `XRSessionEvent` for example code.

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

| Specification |
| --- |
| WebXR Device API # dom-xrsessionevent-xrsessionevent |

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

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

 The read-only `XRSessionEvent` interface's
 **`session`** property indicates which
 `XRSession` the event is about.

Value
-----

An `XRSession` object indicating which WebXR session the event refers to.

Examples
--------

 In this example, the `session` property is used to obtain the session object
 to manage when an event is received.


```js
xrSession.addEventListener("visibilitychange", (e) => {
  switch (e.session.visibilityState) {
    case "hidden":
      myEnableRendering(true);
      break;
    case "visible":
    case "visible-blurred":
      myEnableRendering(false);
      break;
  }
});
```


This calls a function that reacts to the session's visibility state change.

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

| Specification |
| --- |
| WebXR Device API # dom-xrsessionevent-session |

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

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
VisualViewport: resize event
============================

The **`resize`** event of the `VisualViewport` interface is fired when the visual viewport is resized.

Syntax
------

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


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

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

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

A generic `Event`.

Examples
--------

You can use the `resize` event in an `addEventListener()` method:


```js
visualViewport.addEventListener("resize", () => {
  // …
});
```


Or use the `onresize` event handler property:


```js
visualViewport.onresize = () => {
  // …
};
```

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

| Specification |
| --- |
| CSSOM View Module # eventdef-window-resize |

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

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

The **`pageLeft`** read-only property of the `VisualViewport` interface returns the x coordinate of the left edge of the visual viewport relative to the initial containing block origin, in CSS pixels, or `0` if current document is not fully active.

Value
-----

A double.

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

| Specification |
| --- |
| CSSOM View Module # dom-visualviewport-pageleft |

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

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

The **`pageTop`** read-only property of the `VisualViewport` interface returns the y coordinate of the top edge of the visual viewport relative to the initial containing block origin, in CSS pixels, or `0` if current document is not fully active.

Value
-----

A double.

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

| Specification |
| --- |
| CSSOM View Module # dom-visualviewport-pagetop |

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

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

The **`width`** read-only property of the `VisualViewport` interface returns the width of the visual viewport, in CSS pixels, or `0` if current document is not fully active.

Value
-----

A double.

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

| Specification |
| --- |
| CSSOM View Module # dom-visualviewport-width |

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

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

The **`offsetLeft`** read-only property of the `VisualViewport` interface returns the offset of the left edge of the visual viewport from the left edge of the layout viewport in CSS pixels, or `0` if current document is not fully active.

Value
-----

A double.

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

| Specification |
| --- |
| CSSOM View Module # dom-visualviewport-offsetleft |

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

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

The **`height`** read-only property of the `VisualViewport` interface returns the height of the visual viewport, in CSS pixels, or `0` if current document is not fully active.

Value
-----

A double.

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

| Specification |
| --- |
| CSSOM View Module # dom-visualviewport-height |

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

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

The **`scale`** read-only property of the `VisualViewport` interface returns the pinch-zoom scaling factor applied to the visual viewport, or `0` if current document is not fully active, or `1` if there is no output device.

Value
-----

A double.

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

| Specification |
| --- |
| CSSOM View Module # dom-visualviewport-scale |

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

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
VisualViewport: scroll event
============================

The **`scroll`** event of the `VisualViewport` interface is fired when the visual viewport is scrolled.

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

You can use the `scroll` event in an `addEventListener()` method:


```js
visualViewport.addEventListener("scroll", () => {
  // …
});
```


Or use the `onscroll` event handler property:


```js
visualViewport.onscroll = () => {
  // …
};
```

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

| Specification |
| --- |
| CSSOM View Module # eventdef-document-scroll |

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

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

The **`offsetTop`** read-only property of the `VisualViewport` interface returns the offset of the top edge of the visual viewport from the top edge of the layout viewport in CSS pixels, or `0` if current document is not fully active.

Value
-----

A double.

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

| Specification |
| --- |
| CSSOM View Module # dom-visualviewport-offsettop |

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

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

**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 **`code`** property of the `OTPCredential` interface contains the one-time password (OTP).

Value
-----

A string containing the OTP.

Examples
--------

The below code triggers the browser's permission flow when an SMS message arrives. If permission is granted, then the promise resolves with an `OTPCredential` object. The contained `code` value is then set as the value of an `<input>` form element, which is then submitted.


```js
navigator.credentials
  .get({
    otp: { transport: ["sms"] },
    signal: ac.signal,
  })
  .then((otp) => {
    input.value = otp.code;
    if (form) form.submit();
  })
  .catch((err) => {
    console.error(err);
  });
```


**Note:** For a full explanation of the code, see the WebOTP API landing page. You can also see this code as part of a full working demo.

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

| Specification |
| --- |
| WebOTP API # dom-otpcredential-code |

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

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
Determining the dimensions of elements
======================================

There are several properties you can look at in order to determine the width and height of elements, and it can be tricky to determine which is the right one for your needs. This article is designed to help you make that decision. Note that all these properties are read-only. If you want to set the width and height of an element, use `width` and `height` or the overriding `min-width` and `max-width`, and `min-height` and `max-height` properties.

How much room does it use up?
-----------------------------

If you need to know the total amount of space an element occupies, including the width of the visible content, scrollbars (if any), padding, and border, you want to use the `HTMLElement.offsetWidth` and `HTMLElement.offsetHeight` properties. Most of the time these are the same as width and height of `Element.getBoundingClientRect()`, when there aren't any transforms applied to the element. In case of transforms, the `offsetWidth` and `offsetHeight` returns the element's layout width and height, while `getBoundingClientRect()` returns the rendering width and height. As an example, if the element has `width: 100px;` and `transform: scale(0.5);` the `getBoundingClientRect()` will return 50 as the width, while `offsetWidth` will return 100.

![How the offsetWidth and offsetHeight properties are determined, considering padding, borders, and margin sizes](/en-US/docs/Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements/dimensions-offset.png)

What's the size of the displayed content?
-----------------------------------------

If you need to know how much space the actual displayed content takes up, including padding but not including the border, margins, or scrollbars, you want to use the `Element.clientWidth` and `Element.clientHeight` properties:

![How the clientWidth and clientHeight properties are determined, considering padding, borders, and margin sizes](/en-US/docs/Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements/dimensions-client.png)

How big is the content?
-----------------------

If you need to know the actual size of the content, regardless of how much of it is currently visible, you need to use the `Element.scrollWidth` and `Element.scrollHeight` properties. These return the width and height of the entire content of an element, even if only part of it is presently visible due to the use of scroll bars.

For example, if a 600x400 pixel element is being displayed inside a 300x300 pixel scrollbox, `scrollWidth` will return 600 while `scrollHeight` will return 400.

See also
--------

* https://www.w3.org/TR/cssom-view-1/
* MSDN: Measuring Element Dimension and Location
CSS Declaration
===============

A **CSS declaration** is an abstract concept not exposed as an object in the DOM. It represents a CSS property and value pairing.

A CSS declaration has the following associated properties:

property name

The property name of the declaration, for example `background-color`.

value

The value of the declaration as a list of component values.

important flag

Either set or unset.

case-sensitive flag

Set if the property name is defined to be case-sensitive according to the specification, otherwise unset.

Basic example
-------------

The following example shows a CSS rule with a CSS declaration block for the <h1> element. The CSS declaration block is the lines between the curly braces, it contains two CSS declarations. One for `font-style` and another for `color`.


```css
h1 {
  font-style: italic;
  color: rebeccapurple;
}
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # css-declarations |
CSS Declaration Block
=====================

A **CSS declaration block** is an ordered collection of CSS properties and values. It is represented in the DOM as a `CSSStyleDeclaration`.

Each property and value pairing is known as a CSS declaration. The CSS declaration block has the following associated properties:

computed flag

Set if the `CSSStyleDeclaration` object is a computed rather than specified style. Unset by default.

declarations

The CSS declarations associated with this object.

parent CSS rule

The `CSSRule` that the CSS declaration block is associated with, otherwise null.

owner node

The `element` that the CSS declaration block is associated with, otherwise null.

updating flag

Set when the CSS declaration block is updating the owner node's `style` attribute.

When a `CSSStyleDeclaration` is returned by a CSS Object Model (CSSOM) interface these properties are set to appropriate values as defined by the specification.

Basic example
-------------

The following example shows a CSS rule with a declaration block for the h1 element. The CSS declaration block is the lines between the curly braces.


```css
h1 {
  margin: 0 auto;
  font-family: "Helvetica Neue", "Arial", sans-serif;
  font-style: italic;
  color: rebeccapurple;
}
```


We can return a `CSSStyleDeclaration` representing this CSS declaration block using `CSSStyleRule.style`.


```js
let myRules = document.styleSheets[0].cssRules;
let rule = myRules[0]; // a CSSStyleRule
console.log(rule.style); // a CSSStyleDeclaration object
```

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

| Specification |
| --- |
| CSS Object Model (CSSOM) # css-declaration-blocks |
SharedWorkerGlobalScope: connect event
======================================

The **`connect`** event is fired in shared workers at their `SharedWorkerGlobalScope` when a new client connects.

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("connect", (event) => {});

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

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

A `MessageEvent`. Inherits from `Event`.

Event

MessageEventEvent properties
----------------

*This interface also inherits properties from its parent, `Event`.*

`MessageEvent.data` Read only 

The data sent by the message emitter.

`MessageEvent.origin` Read only 

A string representing the origin of the message emitter.

`MessageEvent.lastEventId` Read only 

A string representing a unique ID for the event.

`MessageEvent.source` Read only 

A `MessageEventSource` (which can be a WindowProxy, `MessagePort`, or `ServiceWorker` object) representing the message emitter.

`MessageEvent.ports` Read only 

An array of `MessagePort` objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker).

Examples
--------

This example shows a shared worker file — when a connection to the worker occurs from a main thread via a `MessagePort`, the `onconnect` event handler fires. The event object is a `MessageEvent`.

The connecting port can be referenced through the event object's `ports` parameter; this reference can have an `onmessage` handler attached to it to handle messages coming in through the port, and its `postMessage()` method can be used to send messages back to the main thread using the worker.


```js
self.onconnect = (e) => {
  const port = e.ports[0];

  port.onmessage = (e) => {
    const workerResult = `Result: ${e.data[0] \* e.data[1]}`;
    port.postMessage(workerResult);
  };

  port.start();
};
```


For a complete running example, see our Basic shared worker example (run shared worker.)

### addEventListener equivalent

You could also set up an event handler using the `addEventListener()` method:


```js
self.addEventListener("connect", (e) => {
  const port = e.ports[0];

  port.onmessage = (e) => {
    const workerResult = `Result: ${e.data[0] \* e.data[1]}`;
    port.postMessage(workerResult);
  };
});
```

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

| Specification |
| --- |
| HTML Standard # event-workerglobalscope-connect |
| HTML Standard # handler-sharedworkerglobalscope-onconnect |

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

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

See also
--------

* Using web workers
* `SharedWorkerGlobalScope`
SharedWorkerGlobalScope: close() method
=======================================

The **`close()`** method of the `SharedWorkerGlobalScope` interface discards any tasks queued in the `SharedWorkerGlobalScope`'s event loop, effectively closing this particular scope.

Syntax
------


```js
close()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

If you want to close your worker instance from inside the worker itself, you can call the following:


```js
close();
```


`close()` and `self.close()` are effectively equivalent — both represent `close()` being called from inside the worker's inner scope.

**Note:** There is also a way to stop the worker from the main thread: the `Worker.terminate` method.

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

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

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

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

See also
--------

`DedicatedWorkerGlobalScope`
SharedWorkerGlobalScope: name property
======================================

 The **`name`** read-only property of the
 `SharedWorkerGlobalScope` interface returns the name that the
 `SharedWorker` was (optionally) given when it was created. This is the name
 that the `SharedWorker()` constructor can pass
 to get a reference to the `SharedWorkerGlobalScope`.

Value
-----

A string.

Examples
--------

If a shared worker is created using a constructor with a `name` option:


```js
const myWorker = new SharedWorker("worker.js", { name: "mySharedWorker" });
```


 the `SharedWorkerGlobalScope` will now have a name of "mySharedWorker",
 returnable by running


```js
self.name;
```


from inside the shared worker.

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

| Specification |
| --- |
| HTML Standard # dom-sharedworkerglobalscope-name-dev |

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

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

See also
--------

* `SharedWorkerGlobalScope`