Element: scrollIntoView() method - Web APIs

Element: scrollIntoView() method
================================

Baseline Widely available
-------------------------

This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2020.

* Learn more
* See full compatibility
* Report feedback

 The `Element` interface's
 **`scrollIntoView()`** method scrolls the element's ancestor
 containers such that the element on which `scrollIntoView()` is called is
 visible to the user.

Syntax
------

```js
scrollIntoView()
scrollIntoView(alignToTop)
scrollIntoView(scrollIntoViewOptions)
```

### Parameters

`alignToTop` Optional

A boolean value:

* If `true`, the top of the element will be aligned to the top of the
 visible area of the scrollable ancestor. Corresponds to
 `scrollIntoViewOptions: {block: "start", inline: "nearest"}`. This is
 the default value.
* If `false`, the bottom of the element will be aligned to the bottom
 of the visible area of the scrollable ancestor. Corresponds to
 `scrollIntoViewOptions: {block: "end", inline: "nearest"}`.

`scrollIntoViewOptions` Optional

Experimental

An Object with the following properties:

`behavior` Optional

Determines whether scrolling is instant or animates smoothly. This option is a string which must take one of the following values:

* `smooth`: scrolling should animate smoothly
* `instant`: scrolling should happen instantly in a single jump
* `auto`: scroll behavior is determined by the computed value of `scroll-behavior`

`block` Optional

 Defines vertical alignment.
 One of `start`, `center`, `end`, or
 `nearest`. Defaults to `start`.

`inline` Optional

 Defines horizontal alignment.
 One of `start`, `center`, `end`, or
 `nearest`. Defaults to `nearest`.

### Return value

None (`undefined`).

Examples
--------

```js
const element = document.getElementById("box");

element.scrollIntoView();
element.scrollIntoView(false);
element.scrollIntoView({ block: "end" });
element.scrollIntoView({ behavior: "smooth", block: "end", inline: "nearest" });
```

Notes
-----

 The element may not be scrolled completely to the top or bottom depending on the layout
 of other elements.

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

| Specification |
| --- |
| CSSOM View Module # dom-element-scrollintoview |

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

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

See also
--------

* `Element.scrollIntoViewIfNeeded()`
Non-standard


Element: ariaAutoComplete property - Web APIs

Element: ariaAutoComplete property
==================================

The **`ariaAutoComplete`** property of the `Element` interface reflects the value of the `aria-autocomplete` attribute, which indicates whether inputting text could trigger display of one or more predictions of the user's intended value for a combobox, searchbox, or textbox and specifies how predictions would be presented if they were made.

Value
-----

A string with one of the following values:

`"inline"`

When a user is providing input, text suggesting one way to complete the provided input may be dynamically inserted after the caret.

`"list"`

When a user is providing input, an element containing a collection of values that could complete the provided input may be displayed.

`"both"`

When a user is providing input, an element containing a collection of values that could complete the provided input may be displayed. If displayed, one value in the collection is automatically selected, and the text needed to complete the automatically selected value appears after the caret in the input.

`"none"`

When a user is providing input, there is no display of an automatic suggestion that attempts to predict how the user intends to complete the input.

Examples
--------

In this example, the `aria-autocomplete` attribute on the element with an ID of `animal` is set to "`inline`". Using `ariaAutoComplete` we update the value to "`list`", which is the expected value for a combobox that invokes a `listbox` popup.

```html
<div class="animals-combobox">
  <label for="animal">Animal</label>
  <input
 id="animal"
 type="text"
 role="combobox"
 aria-autocomplete="inline"
 aria-controls="animals-listbox"
 aria-expanded="false"
 aria-haspopup="listbox" />
  <ul id="animals-listbox" role="listbox" aria-label="Animals">
    <li id="animal-cat" role="option">Cat</li>
    <li id="animal-dog" role="option">Dog</li>
  </ul>
</div>
```

```js
let el = document.getElementById("animal");
console.log(el.ariaAutoComplete); // inline
el.ariaAutoComplete = "list";
console.log(el.ariaAutoComplete); // list
```

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

| Specification |
| --- |
| Accessible Rich Internet Applications (WAI-ARIA) # dom-ariamixin-ariaautocomplete |

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

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


Element: touchend event - Web APIs

Element: touchend event
=======================

The `touchend` event fires when one or more touch points are removed from the touch surface. Remember that it is possible to get a `touchcancel` event instead.

Syntax
------

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

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

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

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

A `TouchEvent`. Inherits from `Event`.

Event

UIEvent

TouchEventEvent properties
----------------

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

`TouchEvent.altKey` Read only

A Boolean value indicating whether or not the alt key was down when the touch event was fired.

`TouchEvent.changedTouches` Read only

A `TouchList` of all the `Touch` objects representing individual points of contact whose states changed between the previous touch event and this one.

`TouchEvent.ctrlKey` Read only

A Boolean value indicating whether or not the control key was down when the touch event was fired.

`TouchEvent.metaKey` Read only

A Boolean value indicating whether or not the meta key was down when the touch event was fired.

`TouchEvent.shiftKey` Read only

A Boolean value indicating whether or not the shift key was down when the touch event was fired.

`TouchEvent.targetTouches` Read only

A `TouchList` of all the `Touch` objects that are both currently in contact with the touch surface **and** were also started on the same element that is the target of the event.

`TouchEvent.touches` Read only

A `TouchList` of all the `Touch` objects representing all current points of contact with the surface, regardless of target or changed status.

`TouchEvent.rotation`
Non-standard
 Read only

Change in rotation (in degrees) since the event's beginning. Positive values indicate clockwise rotation; negative values indicate counterclockwise rotation. Initial value: `0.0`.

`TouchEvent.scale`
Non-standard
 Read only

Distance between two digits since the event's beginning. Expressed as a floating-point multiple of the initial distance between the digits at the beginning of the event. Values below 1.0 indicate an inward pinch (zoom out). Values above 1.0 indicate an outward unpinch (zoom in). Initial value: `1.0`.

Examples
--------

Code samples for those events are available on the dedicated page: Touch events.

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

| Specification |
| --- |
| Touch Events # event-touchend |
| Touch Events # dom-globaleventhandlers-ontouchend |

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

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

See also
--------

* Touch events


Element: ariaColCount property - Web APIs

Element: ariaColCount property
==============================

The **`ariaColCount`** property of the `Element` interface reflects the value of the `aria-colcount` attribute, which defines the number of columns in a table, grid, or treegrid.

Value
-----

A string.

Examples
--------

In this example the `aria-colcount` attribute on the element with an ID of `semantic-table` is set to "2". Using `ariaColCount` we update the value to "3".

```html
<table
 id="semantic-table"
 role="table"
 aria-label="Semantic Elements"
 aria-describedby="semantic\_elements\_table\_desc"
 aria-rowcount="100"
 aria-colcount="2">
  <caption id="semantic\_elements\_table\_desc">
    Semantic Elements to use instead of ARIA's roles
  </caption>
  <thead role="rowgroup">
    <tr role="row">
      <th role="columnheader" aria-sort="none" aria-rowindex="1">ARIA Role</th>
      <th role="columnheader" aria-sort="none" aria-rowindex="1">
        Semantic Element
      </th>
    </tr>
  </thead>
  <tbody role="rowgroup">
    <tr role="row">
      <td role="cell" aria-rowindex="11">header</td>
      <td role="cell" aria-rowindex="11">h1</td>
    </tr>
    <tr role="row">
      <td role="cell" aria-rowindex="16">header</td>
      <td role="cell" aria-rowindex="16">h6</td>
    </tr>
    <tr role="row">
      <td role="cell" aria-rowindex="18">rowgroup</td>
      <td role="cell" aria-rowindex="18">thead</td>
    </tr>
    <tr role="row">
      <td role="cell" aria-rowindex="24">term</td>
      <td role="cell" aria-rowindex="24">dt</td>
    </tr>
  </tbody>
</table>
```

```js
let el = document.getElementById("semantic-table");
console.log(el.ariaColCount); // 2
el.ariaColCount = "3";
console.log(el.ariaColCount); // 3
```

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

| Specification |
| --- |
| Accessible Rich Internet Applications (WAI-ARIA) # dom-ariamixin-ariacolcount |

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

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

* ARIA: table role


Element: ariaRowSpan property - Web APIs

Element: ariaRowSpan property
=============================

The **`ariaRowSpan`** property of the `Element` interface reflects the value of the `aria-rowspan` attribute, which defines the number of rows spanned by a cell or gridcell within a table, grid, or treegrid.

Value
-----

A string which contains an integer.

Examples
--------

In this example the `aria-rowspan` attribute on the element with an ID of `spanning-heading` is set to "3". Using `ariaRowSpan` we update the value to "2".

```html
<table>
  <tr>
    <th id="spanning-heading" rowspan="3" aria-rowspan="3">Spanning heading</th>
    <th>Heading</th>
  </tr>
  <tr>
    <td>One</td>
  </tr>
  <tr>
    <td>Two</td>
  </tr>
</table>
```

```js
let el = document.getElementById("spanning-heading");
console.log(el.ariaRowSpan);
el.ariaRowSpan = "2";
console.log(el.ariaRowSpan);
```

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

| Specification |
| --- |
| Accessible Rich Internet Applications (WAI-ARIA) # dom-ariamixin-ariarowspan |

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

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

See also
--------

* ARIA: table role


Element: beforexrselect event - Web APIs

Element: beforexrselect event
=============================

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

The **`beforexrselect`** event is fired before WebXR select events (`select`, `selectstart`, `selectend`) are dispatched. It can be used to suppress XR world input events while the user is interacting with a DOM overlay UI.

This event bubbles, is cancelable and is composed.

Syntax
------

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

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

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

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

An `XRSessionEvent`. Inherits from `Event`.

Event

XRSessionEventEvent properties
----------------

`session` Read only

The `XRSession` to which the event refers.

Event availability
------------------

The **`beforexrselect`** event is a global event and available to the following interfaces:

* `Window`
* `Document`
* `HTMLElement`
* `SVGElement`
* `MathMLElement`
Examples
--------

To suppress WebXR select events (`select`, `selectstart`, `selectend`), an application can listen for the `beforexrselect` event. The event bubbles, so a call to `preventDefault()` on the DOM overlay element will prevent any WebXR select events within this container allowing interaction with the DOM element and avoiding duplicate event input to the XR world.

```js
document
  .getElementById("xr-overlay")
  .addEventListener("beforexrselect", (ev) => ev.preventDefault());
```

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

| Specification |
| --- |
| WebXR DOM Overlays Module # onbeforexrselect |

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

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

See also
--------

* `select` event
* `selectstart` event
* `selectend` event


Element: gotpointercapture event - Web APIs

Element: gotpointercapture event
================================

The **`gotpointercapture`** event is fired when an element captures a pointer using `setPointerCapture()`.

Syntax
------

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

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

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

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

A `PointerEvent`. Inherits from `Event`.

Event

UIEvent

MouseEvent

PointerEventEvent properties
----------------

*This interface inherits properties from `MouseEvent` and `Event`.*

`PointerEvent.altitudeAngle` Read only
Experimental

Represents the angle between a transducer (a pointer or stylus) axis and the X-Y plane of a device screen.

`PointerEvent.azimuthAngle` Read only
Experimental

Represents the angle between the Y-Z plane and the plane containing both the transducer (a pointer or stylus) axis and the Y axis.

`PointerEvent.pointerId` Read only

A unique identifier for the pointer causing the event.

`PointerEvent.width` Read only

The width (magnitude on the X axis), in CSS pixels, of the contact geometry of the pointer.

`PointerEvent.height` Read only

The height (magnitude on the Y axis), in CSS pixels, of the contact geometry of the pointer.

`PointerEvent.pressure` Read only

The normalized pressure of the pointer input in the range `0` to `1`, where `0` and `1` represent the minimum and maximum pressure the hardware is capable of detecting, respectively.

`PointerEvent.tangentialPressure` Read only

The normalized tangential pressure of the pointer input (also known as barrel pressure or cylinder stress) in the range `-1` to `1`, where `0` is the neutral position of the control.

`PointerEvent.tiltX` Read only

The plane angle (in degrees, in the range of `-90` to `90`) between the Y–Z plane and the plane containing both the pointer (e.g. pen stylus) axis and the Y axis.

`PointerEvent.tiltY` Read only

The plane angle (in degrees, in the range of `-90` to `90`) between the X–Z plane and the plane containing both the pointer (e.g. pen stylus) axis and the X axis.

`PointerEvent.twist` Read only

The clockwise rotation of the pointer (e.g. pen stylus) around its major axis in degrees, with a value in the range `0` to `359`.

`PointerEvent.pointerType` Read only

Indicates the device type that caused the event (mouse, pen, touch, etc.).

`PointerEvent.isPrimary` Read only

Indicates if the pointer represents the primary pointer of this pointer type.

Examples
--------

This example gets a `<p>` element and listens for the `gotpointercapture` event. It then calls `setPointerCapture()` on the element on a `pointerdown` event, which will trigger `gotpointercapture`.

```js
const para = document.querySelector("p");

para.addEventListener("gotpointercapture", () => {
  console.log("I've been captured!");
});

para.addEventListener("pointerdown", (event) => {
  para.setPointerCapture(event.pointerId);
});
```

The same example, using the `ongotpointercapture` event handler property:

```js
const para = document.querySelector("p");

para.ongotpointercapture = () => {
  console.log("I've been captured!");
};

para.addEventListener("pointerdown", (event) => {
  para.setPointerCapture(event.pointerId);
});
```

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

| Specification |
| --- |
| Pointer Events # the-gotpointercapture-event |
| Pointer Events # dom-globaleventhandlers-ongotpointercapture |

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

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

See also
--------

* Related events
    + `gotpointercapture`
    + `lostpointercapture`
    + `pointerover`
    + `pointerenter`
    + `pointerdown`
    + `pointermove`
    + `pointerup`
    + `pointercancel`
    + `pointerout`
    + `pointerleave`
    + `pointerrawupdate`


Element: scrollLeft property - Web APIs

Element: scrollLeft property
============================

 The **`Element.scrollLeft`** property gets or sets the number
 of pixels that an element's content is scrolled from its left edge.

 If the element's `direction` is `rtl` (right-to-left), then
 `scrollLeft` is `0` when the scrollbar is at its rightmost
 position (at the start of the scrolled content), and then increasingly negative as you
 scroll towards the end of the content.

It can be specified as any integer value. However:

* If the element can't be scrolled (e.g., it has no overflow), `scrollLeft`
 is set to `0`.
* If specified as a value less than `0` (greater than `0` for
 right-to-left elements), `scrollLeft` is set to `0`.
* If specified as a value greater than the maximum that the content can be scrolled,
 `scrollLeft` is set to the maximum.

**Warning:** On systems using display scaling, `scrollLeft` may give you a decimal
 value.

Value
-----

A number.

Examples
--------

### HTML

```html
<div id="container">
  <div id="content">Click the button to slide right!</div>
</div>

<button id="slide" type="button">Slide right</button>
```

### CSS

```css
#container {
  width: 100px;
  height: 100px;
  border: 1px solid #ccc;
  overflow-x: scroll;
}

#content {
  width: 250px;
  background-color: #ccc;
}
```

### JavaScript

```js
const button = document.getElementById("slide");

button.onclick = () => {
  document.getElementById("container").scrollLeft += 20;
};
```

### Result

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

| Specification |
| --- |
| CSSOM View Module # dom-element-scrollleft |

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

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

See also
--------

* MSDN's Measuring Element Dimension and Location
* `Element.scrollTop`
* `Element.scrollTo()`


Element: getAttributeNS() method - Web APIs

Element: getAttributeNS() method
================================

 The **`getAttributeNS()`** method of the `Element`
 interface returns the string value of the attribute with the specified namespace and
 name. If the named attribute does not exist, the value returned will either be
 `null` or `""` (the empty string); see Notes for
 details.

Syntax
------

```js
getAttributeNS(namespace, name)
```

### Parameters

`namespace`

The namespace in which to look for the specified attribute.

`name`

The name of the attribute to look for.

### Return value

 The string value of the specified attribute. If the attribute doesn't exist, the result
 is `null`.

**Note:** Earlier versions of the DOM specification had
 this method described as returning an empty string for non-existent attributes, but it
 was not typically implemented this way since null makes more sense. The DOM4
 specification now says this method should return null for non-existent attributes.

Examples
--------

 The following SVG document reads the value of the `foo` attribute in a
 custom namespace.

```xml
<svg xmlns="http://www.w3.org/2000/svg"
 xmlns:test="http://www.example.com/2014/test" width="40" height="40">

  <circle id="target" cx="12" cy="12" r="10" stroke="#444"
 stroke-width="2" fill="none" test:foo="Hello namespaced attribute!"/>

  <script>
    const ns = 'http://www.example.com/2014/test';
    const circle = document.getElementById('target');

    console.log(`attribute test:foo: "${circle.getAttributeNS(ns, 'foo')}"`);
  </script>
</svg>
```

 In an HTML document the attribute has to be accessed with `test:foo` since
 namespaces are not supported.

```html
<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" />
    <title>getAttributeNS() test page</title>
  </head>
  <body>
    <svg
 xmlns="http://www.w3.org/2000/svg"
 xmlns:test="http://www.example.com/2014/test"
 width="40"
 height="40">
      <circle
 id="target"
 cx="12"
 cy="12"
 r="10"
 stroke="#444"
 stroke-width="2"
 fill="none"
 test:foo="Foo value" />
    </svg>

    <script>
 const ns = "http://www.example.com/2014/test";
 const circle = document.getElementById("target");
 console.log(`Attribute value: ${circle.getAttribute("test:foo")}`);
 </script>
  </body>
</html>
```

Notes
-----

 Namespaces are only supported in XML documents. HTML documents have to use
 `getAttribute()` instead.

`getAttributeNS()` differs from `getAttribute()` in that it allows you to further specify the requested attribute as
 being part of a particular namespace, as in the example above, where the attribute is
 part of the fictional "specialspace" namespace on Mozilla.

 Prior to the DOM4 specification, this method was specified to return an empty string
 rather than null for non-existent attributes. However, most browsers instead returned
 null. Starting with DOM4, the specification now says to return null. However, some older
 browsers return an empty string. For that reason, you should use
 `hasAttributeNS()` to check for an attribute's
 existence prior to calling `getAttributeNS()` if it is possible that the
 requested attribute does not exist on the specified element.

DOM methods dealing with element's attributes:

| Not namespace-aware, most commonly used methods | Namespace-aware variants (DOM Level 2) | DOM Level 1 methods for dealing with `Attr` nodes directly (seldom used) | DOM Level 2 namespace-aware methods for dealing with `Attr` nodes directly (seldom used) |
| --- | --- | --- | --- |
| `setAttribute` (DOM 1) | `setAttributeNS` | `setAttributeNode` | `setAttributeNodeNS` |
| `getAttribute` (DOM 1) | `getAttributeNS` | `getAttributeNode` | `getAttributeNodeNS` |
| `hasAttribute` (DOM 2) | `hasAttributeNS` | - | - |
| `removeAttribute` (DOM 1) | `removeAttributeNS` | `removeAttributeNode` | - |

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-element-getattributens① |

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

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


Element: computedStyleMap() method - Web APIs

Element: computedStyleMap() method
==================================

 The **`computedStyleMap()`** method of
 the `Element` interface returns a `StylePropertyMapReadOnly`
 interface which provides a read-only representation of a CSS declaration block that is
 an alternative to `CSSStyleDeclaration`.

Syntax
------

```js
computedStyleMap()
```

### Parameters

None.

### Return value

A `StylePropertyMapReadOnly` interface.

Examples
--------

 We start with some simple HTML: a paragraph with a link, and a definition list to which
 we will add all the CSS Property / Value pairs.

```html
<p>
  <a href="https://example.com">Link</a>
</p>
<dl id="regurgitation"></dl>
```

We add a little bit of CSS

```css
a {
  --color: red;
  color: var(--color);
}
```

 We add JavaScript to grab our link and return back a definition list of all the CSS
 property values using `computedStyleMap().`

```js
// get the element
const myElement = document.querySelector("a");

// get the <dl> we'll be populating
const stylesList = document.querySelector("#regurgitation");

// Retrieve all computed styles with computedStyleMap()
const allComputedStyles = myElement.computedStyleMap();

// iterate through the map of all the properties and values, adding a <dt> and <dd> for each
for (const [prop, val] of allComputedStyles) {
  // properties
  const cssProperty = document.createElement("dt");
  cssProperty.appendChild(document.createTextNode(prop));
  stylesList.appendChild(cssProperty);

  // values
  const cssValue = document.createElement("dd");
  cssValue.appendChild(document.createTextNode(val));
  stylesList.appendChild(cssValue);
}
```

 In browsers that support `computedStyleMap()`,
 you'll see a list of all the CSS properties and values.
 In other browsers you'll just see a link.

 Did you realize how many default CSS properties a link had? Update the '`a`'
 to the '`p`', and you'll notice a difference in the `margin-top`
 and `margin-bottom` default computed values.

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

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-element-computedstylemap |

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

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


Element: shadowRoot property - Web APIs

Element: shadowRoot property
============================

Baseline Widely available
-------------------------

This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.

* Learn more
* See full compatibility
* Report feedback

 The `Element.shadowRoot` read-only property
 represents the shadow root hosted by the element.

Use `Element.attachShadow()` to add a shadow root to an existing element.

Value
-----

 A `ShadowRoot` object instance, or `null` if the associated
 shadow root was attached with its `mode` set to
 `closed`. (See `Element.attachShadow()` for further details).

Examples
--------

 The following snippets are taken from our life-cycle-callbacks
 example (see it live also), which creates an element that displays a square of a size and color
 specified in the element's attributes.

 Inside the `<custom-square>` element's class definition we include
 some life cycle callbacks that make a call to an external function,
 `updateStyle()`, which actually applies the size and color to the element.
 You'll see that we are passing it `this` (the custom element itself) as a
 parameter.

```js
class Square extends HTMLElement {
  connectedCallback() {
    console.log("Custom square element added to page.");
    updateStyle(this);
  }

  attributeChangedCallback(name, oldValue, newValue) {
    console.log("Custom square element attributes changed.");
    updateStyle(this);
  }
}
```

 In the `updateStyle()` function itself, we get a reference to the shadow DOM
 using `Element.shadowRoot`. From here we use standard DOM traversal
 techniques to find the `<style>` element inside the shadow DOM and then
 update the CSS found inside it:

```js
function updateStyle(elem) {
  const shadow = elem.shadowRoot;
  const childNodes = Array.from(shadow.childNodes);

  childNodes.forEach((childNode) => {
    if (childNode.nodeName === "STYLE") {
      childNode.textContent = `
 div {
 width: ${elem.getAttribute("l")}px;
 height: ${elem.getAttribute("l")}px;
 background-color: ${elem.getAttribute("c")};
 }
 `;
    }
  });
}
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-element-shadowroot① |

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

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


Element: mousemove event - Web APIs

Element: mousemove event
========================

The `mousemove` event is fired at an element when a pointing device (usually a mouse) is moved while the cursor's hotspot is inside it.

Syntax
------

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

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

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

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

A `MouseEvent`. Inherits from `UIEvent` and `Event`.

Event

UIEvent

MouseEventEvent properties
----------------

*This interface also inherits properties of its parents, `UIEvent` and `Event`.*

`MouseEvent.altKey` Read only

Returns `true` if the `alt` key was down when the mouse event was fired.

`MouseEvent.button` Read only

The button number that was pressed (if applicable) when the mouse event was fired.

`MouseEvent.buttons` Read only

The buttons being pressed (if any) when the mouse event was fired.

`MouseEvent.clientX` Read only

The X coordinate of the mouse pointer in viewport coordinates.

`MouseEvent.clientY` Read only

The Y coordinate of the mouse pointer in viewport coordinates.

`MouseEvent.ctrlKey` Read only

Returns `true` if the `control` key was down when the mouse event was fired.

`MouseEvent.layerX`
Non-standard
 Read only

Returns the horizontal coordinate of the event relative to the current layer.

`MouseEvent.layerY`
Non-standard
 Read only

Returns the vertical coordinate of the event relative to the current layer.

`MouseEvent.metaKey` Read only

Returns `true` if the `meta` key was down when the mouse event was fired.

`MouseEvent.movementX` Read only

The X coordinate of the mouse pointer relative to the position of the last `mousemove` event.

`MouseEvent.movementY` Read only

The Y coordinate of the mouse pointer relative to the position of the last `mousemove` event.

`MouseEvent.offsetX` Read only

The X coordinate of the mouse pointer relative to the position of the padding edge of the target node.

`MouseEvent.offsetY` Read only

The Y coordinate of the mouse pointer relative to the position of the padding edge of the target node.

`MouseEvent.pageX` Read only

The X coordinate of the mouse pointer relative to the whole document.

`MouseEvent.pageY` Read only

The Y coordinate of the mouse pointer relative to the whole document.

`MouseEvent.relatedTarget` Read only

The secondary target for the event, if there is one.

`MouseEvent.screenX` Read only

The X coordinate of the mouse pointer in screen coordinates.

`MouseEvent.screenY` Read only

The Y coordinate of the mouse pointer in screen coordinates.

`MouseEvent.shiftKey` Read only

Returns `true` if the `shift` key was down when the mouse event was fired.

`MouseEvent.mozInputSource`
Non-standard
 Read only

 The type of device that generated the event (one of the `MOZ_SOURCE_*` constants).
 This lets you, for example, determine whether a mouse event was generated by an actual mouse or by a touch event (which might affect the degree of accuracy with which you interpret the coordinates associated with the event).

`MouseEvent.webkitForce`
Non-standard
 Read only

The amount of pressure applied when clicking.

`MouseEvent.x` Read only

Alias for `MouseEvent.clientX`.

`MouseEvent.y` Read only

Alias for `MouseEvent.clientY`.

Examples
--------

The following example uses the `mousedown`, `mousemove`, and `mouseup` events to allow the user to draw on an HTML canvas. Its functionality is simple: the thickness of the line is set to 1, and the color is always black.

When the page loads, constants `myPics` and `context` are created to store a reference to the canvas and the 2d context we will use to draw.

Drawing begins when the `mousedown` event fires. First we store the x and y coordinates of the mouse pointer in the variables `x` and `y`, and then set `isDrawing` to true.

As the mouse moves over the page, the `mousemove` event fires. If `isDrawing` is true, the event handler calls the `drawLine` function to draw a line from the stored `x` and `y` values to the current location.

When the `drawLine()` function returns, we adjust the coordinates and then save them in `x` and `y`.

The `mouseup` event draws the final line segment, sets `x` and `y` to `0`, and stops further drawing by setting `isDrawing` to `false`.

### HTML

```html
<h1>Drawing with mouse events</h1>
<canvas id="myPics" width="560" height="360"></canvas>
```

### CSS

```css
canvas {
  border: 1px solid black;
  width: 560px;
  height: 360px;
}
```

### JavaScript

```js
// When true, moving the mouse draws on the canvas
let isDrawing = false;
let x = 0;
let y = 0;

const myPics = document.getElementById("myPics");
const context = myPics.getContext("2d");

// event.offsetX, event.offsetY gives the (x,y) offset from the edge of the canvas.

// Add the event listeners for mousedown, mousemove, and mouseup
myPics.addEventListener("mousedown", (e) => {
  x = e.offsetX;
  y = e.offsetY;
  isDrawing = true;
});

myPics.addEventListener("mousemove", (e) => {
  if (isDrawing) {
    drawLine(context, x, y, e.offsetX, e.offsetY);
    x = e.offsetX;
    y = e.offsetY;
  }
});

window.addEventListener("mouseup", (e) => {
  if (isDrawing) {
    drawLine(context, x, y, e.offsetX, e.offsetY);
    x = 0;
    y = 0;
    isDrawing = false;
  }
});

function drawLine(context, x1, y1, x2, y2) {
  context.beginPath();
  context.strokeStyle = "black";
  context.lineWidth = 1;
  context.moveTo(x1, y1);
  context.lineTo(x2, y2);
  context.stroke();
  context.closePath();
}
```

### Result

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

| Specification |
| --- |
| UI Events # event-type-mousemove |
| HTML Standard # handler-onmousemove |

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

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

See also
--------

* Introduction to events
* `mousedown`
* `mouseup`
* `click`
* `dblclick`
* `mouseover`
* `mouseout`
* `mouseenter`
* `mouseleave`
* `contextmenu`


Element: keydown event - Web APIs

Element: keydown event
======================

The **`keydown`** event is fired when a key is pressed.

Unlike the deprecated `keypress` event, the `keydown` event is fired for all keys, regardless of whether they produce a character value.

The `keydown` and `keyup` events provide a code indicating which key is pressed, while `keypress` indicates which character was entered. For example, a lowercase "a" will be reported as 65 by `keydown` and `keyup`, but as 97 by `keypress`. An uppercase "A" is reported as 65 by all events.

Keyboard events are only generated by `<input>`, `<textarea>`, `<summary>` and anything with the `contentEditable` or `tabindex` attribute. If not caught, they bubble up the DOM tree until they reach `Document`.

Since Firefox 65, the `keydown` and `keyup` events are now fired during IME composition, to improve cross-browser compatibility for CJKT users (Firefox bug 354358). To ignore all `keydown` events that are part of composition, do something like this (229 is a special value set for a `keyCode` relating to an event that has been processed by an IME):

```js
eventTarget.addEventListener("keydown", (event) => {
  if (event.isComposing || event.keyCode === 229) {
    return;
  }
  // do something
});
```

Syntax
------

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

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

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

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

A `KeyboardEvent`. Inherits from `UIEvent` and `Event`.

Event

UIEvent

KeyboardEventEvent properties
----------------

*This interface also inherits properties of its parents, `UIEvent` and `Event`.*

`KeyboardEvent.altKey` Read only

Returns a boolean value that is `true` if the `Alt` (`Option` or `⌥` on macOS) key was active when the key event was generated.

`KeyboardEvent.code` Read only

Returns a string with the code value of the physical key represented by the event.

**Warning:** This ignores the user's keyboard layout, so that if the user presses the key at the "Y" position in a QWERTY keyboard layout (near the middle of the row above the home row), this will always return "KeyY", even if the user has a QWERTZ keyboard (which would mean the user expects a "Z" and all the other properties would indicate a "Z") or a Dvorak keyboard layout (where the user would expect an "F"). If you want to display the correct keystrokes to the user, you can use `Keyboard.getLayoutMap()`.

`KeyboardEvent.ctrlKey` Read only

Returns a boolean value that is `true` if the `Ctrl` key was active when the key event was generated.

`KeyboardEvent.isComposing` Read only

Returns a boolean value that is `true` if the event is fired between after `compositionstart` and before `compositionend`.

`KeyboardEvent.key` Read only

Returns a string representing the key value of the key represented by the event.

`KeyboardEvent.location` Read only

Returns a number representing the location of the key on the keyboard or other input device. A list of the constants identifying the locations is shown in Keyboard locations.

`KeyboardEvent.metaKey` Read only

Returns a boolean value that is `true` if the `Meta` key (on Mac keyboards, the `⌘ Command` key; on Windows keyboards, the Windows key (`⊞`)) was active when the key event was generated.

`KeyboardEvent.repeat` Read only

Returns a boolean value that is `true` if the key is being held down such that it is automatically repeating.

`KeyboardEvent.shiftKey` Read only

Returns a boolean value that is `true` if the `Shift` key was active when the key event was generated.

Examples
--------

### addEventListener keydown example

This example logs the `KeyboardEvent.code` value whenever you press down a key inside the `<input>` element.

```html
<input placeholder="Click here, then press down a key." size="40" />
<p id="log"></p>
```

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

input.addEventListener("keydown", logKey);

function logKey(e) {
  log.textContent += ` ${e.code}`;
}
```

### onkeydown equivalent

```js
input.onkeydown = logKey;
```

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

| Specification |
| --- |
| UI Events # event-type-keydown |
| HTML Standard # handler-onkeydown |

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

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

See also
--------

* `input`
* `keypress`
* `keyup`


Element: append() method - Web APIs

Element: append() method
========================

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

Differences from `Node.appendChild()`:

* `Element.append()` allows you to also append string
 objects, whereas `Node.appendChild()` only accepts `Node`
 objects.
* `Element.append()` has no return value, whereas
 `Node.appendChild()` returns the appended `Node` object.
* `Element.append()` can append several nodes and strings, whereas
 `Node.appendChild()` can only append one node.
Syntax
------

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

### Parameters

`param1`, …, `paramN`

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

### Return value

None (`undefined`).

### Exceptions

`HierarchyRequestError` `DOMException`

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

Examples
--------

### Appending an element

```js
let div = document.createElement("div");
let p = document.createElement("p");
div.append(p);

console.log(div.childNodes); // NodeList [ <p> ]
```

### Appending text

```js
let div = document.createElement("div");
div.append("Some text");

console.log(div.textContent); // "Some text"
```

### Appending an element and text

```js
let div = document.createElement("div");
let p = document.createElement("p");
div.append("Some text", p);

console.log(div.childNodes); // NodeList [ #text "Some text", <p> ]
```

### The append method is unscopable

 The `append()` method is not scoped into the `with` statement.
 See `Symbol.unscopables` for more information.

```js
let div = document.createElement("div");

with (div) {
  append("foo");
}
// ReferenceError: append is not defined
```

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

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

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

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

See also
--------

* `Element.prepend()`
* `Node.appendChild()`
* `Element.after()`
* `Element.insertAdjacentElement()`
* `NodeList`


Element: getClientRects() method - Web APIs

Element: getClientRects() method
================================

 The **`getClientRects()`** method of the `Element`
 interface returns a collection of `DOMRect` objects that indicate the
 bounding rectangles for each CSS border box in a client.

 Most elements only have one border box each, but a multiline inline-level element (such as a multiline
 `<span>` element, by default) has a border box around each line.

Syntax
------

```js
getClientRects()
```

### Parameters

None.

### Return value

 The returned value is a collection of `DOMRect` objects, one for each CSS
 border box associated with the element. Each `DOMRect` object describes the border box, in pixels, with the top-left
 relative to the top-left of the viewport. For tables with captions, the caption is
 included even though it's outside the border box of the table. When called on SVG
 elements other than an outer-`<svg>`, the "viewport" that the resulting
 rectangles are relative to is the viewport that the element's
 outer-`<svg>` establishes (and to be clear, the rectangles are also
 transformed by the outer-`<svg>`'s `viewBox` transform, if
 any).

 The amount of scrolling that has been done of the viewport area (or any other
 scrollable element) is taken into account when computing the rectangles.

 The returned rectangles do not include the bounds of any child elements that might
 happen to overflow.

 For HTML `<area>` elements, SVG elements that do not render anything
 themselves, `display:none` elements, and generally any elements that are not
 directly rendered, an empty list is returned.

 Rectangles are returned even for CSS boxes that have empty border-boxes. The
 `left`, `top`, `right`, and `bottom`
 coordinates can still be meaningful.

Fractional pixel offsets are possible.

Examples
--------

 These examples draw client rects in various colors. Note that the JavaScript function
 that paints the client rects is connected to the markup via the class
 `withClientRectsOverlay`.

### HTML

 Example 1: This HTML creates three paragraphs with a `<span>` inside,
 each embedded in a `<div>` block. Client rects are painted for the
 paragraph in the second block, and for the `<span>` element in the
 third block.

```html
<h3>A paragraph with a span inside</h3>
<p>
  Both the span and the paragraph have a border set. The client rects are in
  red. Note that the p has only one border box, while the span has multiple
  border boxes.
</p>

<div>
  <strong>Original</strong>
  <p>
    <span>Paragraph that spans multiple lines</span>
  </p>
</div>

<div>
  <strong>p's rect</strong>
  <p class="withClientRectsOverlay">
    <span>Paragraph that spans multiple lines</span>
  </p>
</div>

<div>
  <strong>span's rect</strong>
  <p>
    <span class="withClientRectsOverlay"
 >Paragraph that spans multiple lines</span
 >
  </p>
</div>
```

 Example 2: This HTML creates three ordered lists. Client rects are painted for the
 `<ol>` in the second block, and for each `<li>`
 element in the third block.

```html
<h3>A list</h3>
<p>
  Note that the border box doesn't include the number, so neither do the client
  rects.
</p>

<div>
  <strong>Original</strong>
  <ol>
    <li>Item 1</li>
    <li>Item 2</li>
  </ol>
</div>

<div>
  <strong>ol's rect</strong>
  <ol class="withClientRectsOverlay">
    <li>Item 1</li>
    <li>Item 2</li>
  </ol>
</div>

<div>
  <strong>each li's rect</strong>
  <ol>
    <li class="withClientRectsOverlay">Item 1</li>
    <li class="withClientRectsOverlay">Item 2</li>
  </ol>
</div>
```

 Example 3: This HTML creates two tables with captions. Client rects are painted for the
 `<table>` in the second block.

```html
<h3>A table with a caption</h3>
<p>
  Although the table's border box doesn't include the caption, the client rects
  do include the caption.
</p>

<div>
  <strong>Original</strong>
  <table>
    <caption>
      caption
    </caption>
    <thead>
      <tr>
        <th>thead</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>tbody</td>
      </tr>
    </tbody>
  </table>
</div>

<div>
  <strong>table's rect</strong>
  <table class="withClientRectsOverlay">
    <caption>
      caption
    </caption>
    <thead>
      <tr>
        <th>thead</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>tbody</td>
      </tr>
    </tbody>
  </table>
</div>
```

### CSS

 The CSS draws borders around the paragraph and the `<span>` inside
 each `<div>` block for the first example, around the
 `<ol>` and `<li>` for the second example, and around
 `<table>`, `<th>`, and `<td>`
 elements for the third example.

```css
strong {
  text-align: center;
}
div {
  display: inline-block;
  width: 150px;
}
div p,
ol,
table {
  border: 1px solid blue;
}
span,
li,
th,
td {
  border: 1px solid green;
}
```

### JavaScript

 The JavaScript code draws the client rects for all HTML elements that have CSS class
 `withClientRectsOverlay` assigned.

```js
function addClientRectsOverlay(elt) {
  /\* Absolutely position a div over each client rect so that its border width
 is the same as the rectangle's width.
 Note: the overlays will be out of place if the user resizes or zooms. \*/
  const rects = elt.getClientRects();
  for (const rect of rects) {
    const tableRectDiv = document.createElement("div");
    tableRectDiv.style.position = "absolute";
    tableRectDiv.style.border = "1px solid red";
    const scrollTop =
      document.documentElement.scrollTop || document.body.scrollTop;
    const scrollLeft =
      document.documentElement.scrollLeft || document.body.scrollLeft;
    tableRectDiv.style.margin = tableRectDiv.style.padding = "0";
    tableRectDiv.style.top = `${rect.top + scrollTop}px`;
    tableRectDiv.style.left = `${rect.left + scrollLeft}px`;
    // We want rect.width to be the border width, so content width is 2px less.
    tableRectDiv.style.width = `${rect.width - 2}px`;
    tableRectDiv.style.height = `${rect.height - 2}px`;
    document.body.appendChild(tableRectDiv);
  }
}

(() => {
  /\* Call function addClientRectsOverlay(elt) for all elements with
 assigned class "withClientRectsOverlay" \*/
  const elts = document.getElementsByClassName("withClientRectsOverlay");
  for (const elt of elts) {
    addClientRectsOverlay(elt);
  }
})();
```

### Result

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

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

### Notes

`getClientRects()` was first introduced in the MS IE DHTML object model.

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

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

See also
--------

* `Element.getBoundingClientRect()`


Element: querySelector() method - Web APIs

Element: querySelector() method
===============================

 The **`querySelector()`** method of the `Element`
 interface returns the first element that is a descendant of the element on which it is
 invoked that matches the specified group of selectors.

Syntax
------

```js
querySelector(selectors)
```

### Parameters

`selectors`

 A group of selectors to match
 the descendant elements of the `Element` `baseElement`
 against; this must be valid CSS syntax, or a `SyntaxError` exception will
 occur. The first element found which matches this group of selectors is returned.

### Return value

 The first descendant element of `baseElement` which matches the specified
 group of `selectors`. The entire hierarchy of elements is considered when
 matching, including those outside the set of elements including `baseElement`
 and its descendants; in other words, `selectors` is first applied to the
 whole document, not the `baseElement`, to generate an initial list of
 potential elements. The resulting elements are then examined to see if they are
 descendants of `baseElement`. The first match of those remaining elements is
 returned by the `querySelector()` method.

If no matches are found, the returned value is `null`.

### Exceptions

`SyntaxError` `DOMException`

Thrown if the specified `selectors` are invalid.

Examples
--------

Let's consider a few examples.

### Find a specific element with specific values of an attribute

 In this first example, the first `<style>` element which either has no
 type or has type "text/css" in the HTML document body is returned:

```js
const el = document.body.querySelector(
  "style[type='text/css'], style:not([type])",
);
```

### Get direct descendants using the :scope pseudo-class

This example uses the `:scope` pseudo-class to retrieve direct children of the `parentElement` element.

#### HTML

```html
<div>
  <h6>Page Title</h6>
  <div id="parent">
    <span>Love is Kind.</span>
    <span>
      <span>Love is Patient.</span>
    </span>
    <span>
      <span>Love is Selfless.</span>
    </span>
  </div>
</div>
```

#### CSS

```css
span {
  display: block;
  margin-bottom: 5px;
}
.red span {
  background-color: red;
  padding: 5px;
}
```

#### JavaScript

```js
const parentElement = document.querySelector("#parent");
let allChildren = parentElement.querySelectorAll(":scope > span");
allChildren.forEach((item) => item.classList.add("red"));
```

#### Result

### The entire hierarchy counts

 This example demonstrates that the hierarchy of the entire document is considered when
 applying `selectors`, so that levels outside the specified
 `baseElement` are still considered when locating matches.

#### HTML

```html
<div>
  <h5>Original content</h5>
  <p>
    inside paragraph
    <span>inside span</span>
    inside paragraph
  </p>
</div>
<div>
  <h5>Output</h5>
  <div id="output"></div>
</div>
```

#### JavaScript

```js
const baseElement = document.querySelector("p");
document.getElementById("output").innerHTML =
  baseElement.querySelector("div span").innerHTML;
```

#### Result

The result looks like this:

 Notice how the `"div span"` selector still successfully matches the
 `<span>` element, even though the `baseElement`'s child nodes
 do not include the `<div>` element (it is still part of the specified
 selector).

### More examples

 See `Document.querySelector()` for additional examples of the proper
 format for the `selectors`.

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

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

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

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

See also
--------

* Locating DOM elements using selectors
* Attribute selectors in the CSS
 Guide
* Attribute selectors in the MDN Learning Area
* `Element.querySelectorAll()`
* `Document.querySelector()` and
 `Document.querySelectorAll()`
* `DocumentFragment.querySelector()` and
 `DocumentFragment.querySelectorAll()`
* Other methods that take selectors: `element.closest()` and
 `element.matches()`.


Element: checkVisibility() method - Web APIs

Element: checkVisibility() method
=================================

The **`checkVisibility()`** method of the `Element` interface checks whether the element is visible.

The method returns `false` in either of the following situations:

* The element doesn't have an associated box, for example because the CSS `display` property is set to `none` or `contents`.
* The element is not being rendered because the element or an ancestor element sets the `content-visibility` property to `hidden`.

 The optional parameter enables additional checks to test for other interpretations of what "visible" means.
 For example, you can further check whether an element has an opacity of `0`, if the value of the element `visibility` property makes it invisible, or if the element `content-visibility` property has a value of `auto` and its rendering is currently being skipped.

Syntax
------

```js
checkVisibility(options)
```

### Parameters

`options` Optional

 An object indicating additional checks to run.
 The possible options are:

`contentVisibilityAuto`

`true` to check if the element `content-visibility` property has (or inherits) the value `auto`, and it is currently skipping its rendering.
 `false` by default.

`opacityProperty`

`true` to check if the element `opacity` property has (or inherits) a value of `0`.
 `false` by default.

`visibilityProperty`

`true` to check if the element is invisible due to the value of its `visibility` property.
 `false` by default.

**Note:** Invisible elements include those that have `visibility: hidden`, and some element types that have `visibility: collapse`.

`checkOpacity`

A historic alias for `opacityProperty`.

`checkVisibilityCSS`

A historic alias for `visibilityProperty`.

### Return value

`false` if any of the following conditions are met, otherwise `true`:

* The element doesn't have an associated box.
* The element `content-visibility` property has (or inherits) a value of `hidden`.
* `opacityProperty` (or `checkOpacity`) is `true` and the element `opacity` property has (or inherits) a value of `0`.
* `visibilityProperty` (or `checkVisibilityCSS`) is `true` and the element is invisible due to the value of its `visibility` property.
* `contentVisibilityAuto` is `true`, the `content-visibility` property has (or inherits) a value of `auto`, and element rendering is being skipped.
Examples
--------

### Test checkVisibility() with varied CSS

The following example allows you to test how the result of `checkVisibility()` might change with different values for `display`, `content-visibility`, `visibility`, and `opacity` CSS properties.

#### HTML

 The HTML defines a `<select>` element for the CSS properties that affect the results of `checkVisibility()`.
 The first (default selected) values should result in `checkVisibility()` returning `true` when applied to an element, while the other values affect the visibility.

```html
<select id="css\_display" name="css\_display">
  <option value="block" selected>display: block</option>
  <option value="none">display: none</option>
  <option value="content">display: content</option>
</select>

<select id="css\_content\_visibility" name="css\_content\_visibility">
  <option value="visible" selected>content-visibility: visible</option>
  <option value="hidden">content-visibility: hidden</option>
  <option value="auto">content-visibility: auto</option>
</select>

<select id="css\_opacity" name="css\_opacity">
  <option value="1" selected>opacity: 1</option>
  <option value="0">opacity: 0</option>
</select>

<select id="css\_visibility" name="css\_visibility">
  <option value="visible" selected>visibility: visible</option>
  <option value="hidden">visibility: hidden</option>
  <option value="collapse">visibility: collapse</option>
</select>
```

 Next we have a `<pre>` that is used to output the result of the `checkVisibility()` check when no options are passed in the parameter, and for each separate option value.
 At the end we have the element that will be tested (to which we will apply the selected CSS property values).

```html
<pre id="output\_result"></pre>
<div id="test\_element">The element to be checked for visibility.</div>
```

#### CSS

The CSS just highlights the element to be tested.

```css
#test\_element {
  border: solid;
  border-color: blue;
}
```

#### JavaScript

 The code below gets each of the `<select>` elements.
 The `updateCSS()` method is called on start and whenever the select elements change in order to apply the selected CSS to the target element,

```js
const displayCssSelect = document.getElementById("css\_display");
const contentVisibilityCssSelect = document.getElementById(
  "css\_content\_visibility",
);
const displayCssOpacity = document.getElementById("css\_opacity");
const displayCssVisibility = document.getElementById("css\_visibility");

const outputResult = document.getElementById("output\_result");
const elementToCheck = document.getElementById("test\_element");

updateCSS();

const cssSelectors = document.querySelectorAll("select");
cssSelectors.forEach((select) => {
  select.addEventListener("change", (event) => {
    updateCSS();
  });
});

function updateCSS() {
  // Apply selected CSS properties to target element
  elementToCheck.style.display = displayCssSelect.value;
  elementToCheck.style.contentVisibility = contentVisibilityCssSelect.value;
  elementToCheck.style.opacity = displayCssOpacity.value;
  elementToCheck.style.visibility = displayCssVisibility.value;

  // Call checkVisibility() on element using default and each of options
  const defaultVisibilityCheck = elementToCheck.checkVisibility();
  const opacityVisibilityCheck = elementToCheck.checkVisibility({
    opacityProperty: true,
  });
  const cssVisibilityCheck = elementToCheck.checkVisibility({
    visibilityProperty: true,
  });
  const contentVisibilityAutoCheck = elementToCheck.checkVisibility({
    contentVisibilityAuto: true,
  });

  // Output the results of the tests
  outputResult.innerText = `Checks on element below (may be hidden):
- Result of checkVisibility(): ${defaultVisibilityCheck}
- Result of checkVisibility({opacityProperty: true}): ${opacityVisibilityCheck}
- Result of checkVisibility({visibilityProperty: true}): ${cssVisibilityCheck}
- Result of checkVisibility({contentVisibilityAuto: true}): ${contentVisibilityAutoCheck}`;
}
```

#### Result

 The results are shown below.
 If you change the selection the results will be applied to the test element (blue outline) and the results of the `checkVisibility()` for each setting should be displayed.
 So for example, if you set the `opacity: 0` that test (only) should indicate `false`.
 However if you set `display: none` then all tests should return `false.

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

| Specification |
| --- |
| CSSOM View Module # dom-element-checkvisibility |

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

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


Element: pointerup event - Web APIs

Element: pointerup event
========================

The `pointerup` event is fired when a pointer is no longer active. Remember that it is possible to get a `pointercancel` event instead.

Syntax
------

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

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

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

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

A `PointerEvent`. Inherits from `Event`.

Event

UIEvent

MouseEvent

PointerEventEvent properties
----------------

*This interface inherits properties from `MouseEvent` and `Event`.*

`PointerEvent.altitudeAngle` Read only
Experimental

Represents the angle between a transducer (a pointer or stylus) axis and the X-Y plane of a device screen.

`PointerEvent.azimuthAngle` Read only
Experimental

Represents the angle between the Y-Z plane and the plane containing both the transducer (a pointer or stylus) axis and the Y axis.

`PointerEvent.pointerId` Read only

A unique identifier for the pointer causing the event.

`PointerEvent.width` Read only

The width (magnitude on the X axis), in CSS pixels, of the contact geometry of the pointer.

`PointerEvent.height` Read only

The height (magnitude on the Y axis), in CSS pixels, of the contact geometry of the pointer.

`PointerEvent.pressure` Read only

The normalized pressure of the pointer input in the range `0` to `1`, where `0` and `1` represent the minimum and maximum pressure the hardware is capable of detecting, respectively.

`PointerEvent.tangentialPressure` Read only

The normalized tangential pressure of the pointer input (also known as barrel pressure or cylinder stress) in the range `-1` to `1`, where `0` is the neutral position of the control.

`PointerEvent.tiltX` Read only

The plane angle (in degrees, in the range of `-90` to `90`) between the Y–Z plane and the plane containing both the pointer (e.g. pen stylus) axis and the Y axis.

`PointerEvent.tiltY` Read only

The plane angle (in degrees, in the range of `-90` to `90`) between the X–Z plane and the plane containing both the pointer (e.g. pen stylus) axis and the X axis.

`PointerEvent.twist` Read only

The clockwise rotation of the pointer (e.g. pen stylus) around its major axis in degrees, with a value in the range `0` to `359`.

`PointerEvent.pointerType` Read only

Indicates the device type that caused the event (mouse, pen, touch, etc.).

`PointerEvent.isPrimary` Read only

Indicates if the pointer represents the primary pointer of this pointer type.

Examples
--------

Using `addEventListener()`:

```js
const para = document.querySelector("p");

para.addEventListener("pointerup", (event) => {
  console.log("Pointer up");
});
```

Using the `onpointerup` event handler property:

```js
const para = document.querySelector("p");

para.onpointerup = (event) => {
  console.log("Pointer up");
};
```

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

| Specification |
| --- |
| Pointer Events # the-pointerup-event |
| Pointer Events # dom-globaleventhandlers-onpointerup |

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

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

See also
--------

* Related events
    + `gotpointercapture`
    + `lostpointercapture`
    + `pointerover`
    + `pointerenter`
    + `pointerdown`
    + `pointermove`
    + `pointerup`
    + `pointercancel`
    + `pointerout`
    + `pointerleave`
    + `pointerrawupdate`


Element: webkitmouseforceup event - Web APIs

Element: webkitmouseforceup event
=================================

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The non-standard **`webkitmouseforceup`** event is fired by Safari at an `Element` some time after the `webkitmouseforcedown` event, when pressure on the button has been reduced sufficiently to end the "force click".

**`webkitmouseforceup`** is a proprietary, WebKit-specific event. It is part of the `Force Touch Events` feature.

Syntax
------

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

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

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

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

A `MouseEvent`. Inherits from `UIEvent` and `Event`.

Event

UIEvent

MouseEventEvent properties
----------------

*This interface also inherits properties of its parents, `UIEvent` and `Event`.*

`MouseEvent.altKey` Read only

Returns `true` if the `alt` key was down when the mouse event was fired.

`MouseEvent.button` Read only

The button number that was pressed (if applicable) when the mouse event was fired.

`MouseEvent.buttons` Read only

The buttons being pressed (if any) when the mouse event was fired.

`MouseEvent.clientX` Read only

The X coordinate of the mouse pointer in viewport coordinates.

`MouseEvent.clientY` Read only

The Y coordinate of the mouse pointer in viewport coordinates.

`MouseEvent.ctrlKey` Read only

Returns `true` if the `control` key was down when the mouse event was fired.

`MouseEvent.layerX`
Non-standard
 Read only

Returns the horizontal coordinate of the event relative to the current layer.

`MouseEvent.layerY`
Non-standard
 Read only

Returns the vertical coordinate of the event relative to the current layer.

`MouseEvent.metaKey` Read only

Returns `true` if the `meta` key was down when the mouse event was fired.

`MouseEvent.movementX` Read only

The X coordinate of the mouse pointer relative to the position of the last `mousemove` event.

`MouseEvent.movementY` Read only

The Y coordinate of the mouse pointer relative to the position of the last `mousemove` event.

`MouseEvent.offsetX` Read only

The X coordinate of the mouse pointer relative to the position of the padding edge of the target node.

`MouseEvent.offsetY` Read only

The Y coordinate of the mouse pointer relative to the position of the padding edge of the target node.

`MouseEvent.pageX` Read only

The X coordinate of the mouse pointer relative to the whole document.

`MouseEvent.pageY` Read only

The Y coordinate of the mouse pointer relative to the whole document.

`MouseEvent.relatedTarget` Read only

The secondary target for the event, if there is one.

`MouseEvent.screenX` Read only

The X coordinate of the mouse pointer in screen coordinates.

`MouseEvent.screenY` Read only

The Y coordinate of the mouse pointer in screen coordinates.

`MouseEvent.shiftKey` Read only

Returns `true` if the `shift` key was down when the mouse event was fired.

`MouseEvent.mozInputSource`
Non-standard
 Read only

 The type of device that generated the event (one of the `MOZ_SOURCE_*` constants).
 This lets you, for example, determine whether a mouse event was generated by an actual mouse or by a touch event (which might affect the degree of accuracy with which you interpret the coordinates associated with the event).

`MouseEvent.webkitForce`
Non-standard
 Read only

The amount of pressure applied when clicking.

`MouseEvent.x` Read only

Alias for `MouseEvent.clientX`.

`MouseEvent.y` Read only

Alias for `MouseEvent.clientY`.

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

*Not part of any specification.* Apple has a description at the Mac Developer Library.

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

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

See also
--------

* Introduction to events
* `webkitmouseforcewillbegin`
* `webkitmouseforcedown`
* `webkitmouseforcechanged`


Element: DOMMouseScroll event - Web APIs

Element: DOMMouseScroll event
=============================

**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 DOM `DOMMouseScroll` event is fired asynchronously when mouse wheel or similar device is operated and the accumulated scroll amount is over 1 line or 1 page since last event. It's represented by the `MouseScrollEvent` interface. This event was only implemented by Firefox. You should instead use the standard `wheel` event.

If you want to prevent the default action of mouse wheel events, it's not enough to handle only this event on Gecko because If scroll amount by a native mouse wheel event is less than 1 line (or less than 1 page when the system setting is by page scroll), other mouse wheel events may be fired without this event.

On Gecko 17 (Firefox 17) or later, you need to call `preventDefault()` of `wheel` events which must be fired for every native event.

Use the standardized `wheel` event if available.

Syntax
------

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

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

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

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

A `WheelEvent`. Inherits from `MouseEvent`, `UIEvent` and `Event`.

Event

UIEvent

MouseEvent

WheelEventEvent properties
----------------

The event has only one additional property beyond standard events.

### detail

The `detail` property describes the scroll more precisely, with positive values indicating scrolling downward and negative values indicating scrolling upward.

If the event represents scrolling up by a page, the value of `detail` is -32768. If the event indicates scrolling down by a page, the value is +32768. Any other value represents the number of lines to scroll, with the direction indicated by the value's sign.

**Note:** Trusted events are never sent with a value of 0 for `detail`.

Trusted events are never fired with 0.

**Note:** If the platform's native mouse wheel events only provide scroll distance by pixels, or if the speed can be customized by the user, the value is computed using the line height of the nearest scrollable ancestor element of the event's target. If that element's font size is smaller than `mousewheel.min_line_scroll_amount`, that preference's value is used as the line height.

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

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

See also
--------

* `MouseScrollEvent`
* Gecko's legacy pixel scroll event: `MozMousePixelScroll`
* Non-Gecko browsers' legacy mouse wheel event: `mousewheel`
* Standardized wheel event: `wheel`


Element: className property - Web APIs

Element: className property
===========================

 The **`className`** property of the
 `Element` interface gets and sets the value of the `class` attribute
 of the specified element.

Value
-----

A string variable representing the class or space-separated classes of the current element.

Examples
--------

```js
const el = document.getElementById("item");
el.className = el.className === "active" ? "inactive" : "active";
```

Notes
-----

 The name `className` is used for this property instead of `class`
 because of conflicts with the "class" keyword in many languages which are used to
 manipulate the DOM.

`className` can also be an instance of `SVGAnimatedString` if
 the `element` is an `SVGElement`. It is better to get/set the
 `className` of an element using `Element.getAttribute` and
 `Element.setAttribute` if you are dealing with SVG elements. However, take
 into account that `Element.getAttribute` returns
 `null`
 instead of `""` if the `element` has an empty `class` attribute.

```js
elm.setAttribute("class", elm.getAttribute("class"));
```

**Note:** The `class` is an **HTML Attribute**, while the
 `className` is a **DOM Property**.

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-element-classname① |

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

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

See also
--------

* `element.classList`


Element: getElementsByClassName() method - Web APIs

Element: getElementsByClassName() method
========================================

 The `Element` method
 **`getElementsByClassName()`** returns a live
 `HTMLCollection` which contains every descendant element which has the
 specified class name or names.

 The method `getElementsByClassName()`
 on the `Document` interface works essentially the same way, except it acts
 on the entire document, starting at the document root.

Syntax
------

```js
getElementsByClassName(names)
```

### Parameters

`names`

 A string containing one or more class names to match on, separated
 by whitespace.

### Return value

 An `HTMLCollection` providing a live-updating list of every element which
 is a member of every class in `names`.

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

 As always, the returned collection is *live*, meaning that it always reflects
 the current state of the DOM tree rooted at the element on which the function was
 called. As new elements that match `names` are added to the subtree, they
 immediately appear in the collection. Similarly, if an existing element that doesn't
 match `names` has its set of classes adjusted so that it matches, it
 immediately appears in the collection.

 The opposite is also true; as elements no longer match the set of names, they are
 immediately removed from the collection.

**Note:** In quirks mode, the
 class names are compared in a case-insensitive fashion. Otherwise, they're case
 sensitive.

Examples
--------

### Matching a single class

 To look for elements that include among their classes a single specified class, we just
 provide that class name when calling `getElementsByClassName()`:

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

 This example finds all elements that have a class of `test`, which are also
 a descendant of the element that has the `id` of `main`:

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

### Matching multiple classes

 To find elements whose class lists include both the `red` and
 `test` classes:

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

### Examining the results

 You can use either the `item()` method on the
 returned `HTMLCollection` or standard array syntax to examine individual
 elements in the collection. However, the following code will not
 work as one might expect because `"matches"` will change as
 soon as any `"colorbox"` class is removed.

```js
const matches = element.getElementsByClassName("colorbox");

for (let i = 0; i < matches.length; i++) {
  matches[i].classList.remove("colorbox");
  matches.item(i).classList.add("hueframe");
}
```

Instead, use another method, such as:

```js
const matches = element.getElementsByClassName("colorbox");

while (matches.length > 0) {
  matches.item(0).classList.add("hueframe");
  matches[0].classList.remove("colorbox");
}
```

 This code finds descendant elements with the `"colorbox"` class, adds the
 class `"hueframe"`, by calling `item(0)`, then removes
 `"colorbox"` (using array notation). Another element (if any are left) will
 then become `item(0)`.

### Filtering the results using array methods

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

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

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-element-getelementsbyclassname |

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

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


Element: pointerover event - Web APIs

Element: pointerover event
==========================

The `pointerover` event is fired when a pointing device is moved into an element's hit test boundaries.

Syntax
------

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

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

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

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

A `PointerEvent`. Inherits from `Event`.

Event

UIEvent

MouseEvent

PointerEventEvent properties
----------------

*This interface inherits properties from `MouseEvent` and `Event`.*

`PointerEvent.altitudeAngle` Read only
Experimental

Represents the angle between a transducer (a pointer or stylus) axis and the X-Y plane of a device screen.

`PointerEvent.azimuthAngle` Read only
Experimental

Represents the angle between the Y-Z plane and the plane containing both the transducer (a pointer or stylus) axis and the Y axis.

`PointerEvent.pointerId` Read only

A unique identifier for the pointer causing the event.

`PointerEvent.width` Read only

The width (magnitude on the X axis), in CSS pixels, of the contact geometry of the pointer.

`PointerEvent.height` Read only

The height (magnitude on the Y axis), in CSS pixels, of the contact geometry of the pointer.

`PointerEvent.pressure` Read only

The normalized pressure of the pointer input in the range `0` to `1`, where `0` and `1` represent the minimum and maximum pressure the hardware is capable of detecting, respectively.

`PointerEvent.tangentialPressure` Read only

The normalized tangential pressure of the pointer input (also known as barrel pressure or cylinder stress) in the range `-1` to `1`, where `0` is the neutral position of the control.

`PointerEvent.tiltX` Read only

The plane angle (in degrees, in the range of `-90` to `90`) between the Y–Z plane and the plane containing both the pointer (e.g. pen stylus) axis and the Y axis.

`PointerEvent.tiltY` Read only

The plane angle (in degrees, in the range of `-90` to `90`) between the X–Z plane and the plane containing both the pointer (e.g. pen stylus) axis and the X axis.

`PointerEvent.twist` Read only

The clockwise rotation of the pointer (e.g. pen stylus) around its major axis in degrees, with a value in the range `0` to `359`.

`PointerEvent.pointerType` Read only

Indicates the device type that caused the event (mouse, pen, touch, etc.).

`PointerEvent.isPrimary` Read only

Indicates if the pointer represents the primary pointer of this pointer type.

Examples
--------

Using `addEventListener()`:

```js
const para = document.querySelector("p");

para.addEventListener("pointerover", (event) => {
  console.log("Pointer moved in");
});
```

Using the `onpointerover` event handler property:

```js
const para = document.querySelector("p");

para.onpointerover = (event) => {
  console.log("Pointer moved in");
};
```

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

| Specification |
| --- |
| Pointer Events # the-pointerover-event |
| Pointer Events # dom-globaleventhandlers-onpointerover |

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

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

See also
--------

* Related events
    + `gotpointercapture`
    + `lostpointercapture`
    + `pointerover`
    + `pointerenter`
    + `pointerdown`
    + `pointermove`
    + `pointerup`
    + `pointercancel`
    + `pointerout`
    + `pointerleave`
    + `pointerrawupdate`


Element: ariaValueText property - Web APIs

Element: ariaValueText property
===============================

The **`ariaValueText`** property of the `Element` interface reflects the value of the `aria-valuetext` attribute, which defines the human-readable text alternative of aria-valuenow for a range widget.

Value
-----

A string.

Examples
--------

In this example the `aria-valuetext` attribute on the element with an ID of `slider` is set to "Sunday" to give a human-readable value for the range. Using `ariaValueText` we update the value to "Monday".

```html
<div
 id="slider"
 role="slider"
 aria-valuenow="1"
 aria-valuemin="1"
 aria-valuemax="7"
 aria-valuetext="Sunday"></div>
```

```js
let el = document.getElementById("slider");
console.log(el.ariaValueText); // Sunday
el.ariaValueText = "Monday";
console.log(el.ariaValueText); // Monday
```

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

| Specification |
| --- |
| Accessible Rich Internet Applications (WAI-ARIA) # dom-ariamixin-ariavaluetext |

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

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


Element: replaceChildren() method - Web APIs

Element: replaceChildren() method
=================================

 The **`Element.replaceChildren()`** method replaces the
 existing children of a `Node` with a specified new set of children. These
 can be string or `Node` objects.

Syntax
------

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

### Parameters

`param1`, …, `paramN`

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

### Return value

None (`undefined`).

### Exceptions

`HierarchyRequestError` `DOMException`

Thrown when the constraints of the node tree are violated.

Examples
--------

### Emptying a node

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

```js
myNode.replaceChildren();
```

### Transferring nodes between elements

`replaceChildren()` enables you to easily transfer nodes between elements,
 without having to resort to verbose looping code. For example, say we have a simple
 application allowing you to choose what food you want for your party. This HTML might
 look something like this:

```html
<h2>Party food option list</h2>

<main>
  <div>
    <label for="no">No thanks!</label>

    <select id="no" multiple size="10">
      <option>Apples</option>
      <option>Oranges</option>
      <option>Grapes</option>
      <option>Bananas</option>
      <option>Kiwi fruits</option>
      <option>Chocolate cookies</option>
      <option>Peanut cookies</option>
      <option>Chocolate bars</option>
      <option>Ham Sandwiches</option>
      <option>Cheese Sandwiches</option>
      <option>Falafel sandwiches</option>
      <option>Ice cream</option>
      <option>Jelly</option>
      <option>Carrot sticks and hummus</option>
      <option>Margherita pizza</option>
      <option>Pepperoni pizza</option>
      <option>Vegan veggie pizza</option>
    </select>
  </div>

  <div class="buttons">
    <button id="to-yes">Transfer to "Yes" --></button>
    <button id="to-no"><-- Transfer to "No"</button>
  </div>

  <div>
    <label for="yes">Yes please!</label>

    <select id="yes" multiple size="10"></select>
  </div>
</main>
```

 It would make sense to use some simple CSS to lay out the two select lists in a line
 alongside one another, with the control buttons in between them:

```css
main {
  display: flex;
}

div {
  margin-right: 20px;
}

label,
button {
  display: block;
}

.buttons {
  display: flex;
  flex-flow: column;
  justify-content: center;
}

select {
  width: 200px;
}
```

 What we want to do is transfer any selected options in the "no" list over to the "yes"
 list when the "yes" button is pressed, and transfer any selected options in the "yes"
 list over to the "no" list when the "no" button is pressed.

 To do this, we give each of the buttons a click event handler, which collects together
 the selected options you want to transfer in one constant, and the existing options in
 the list you are transferring to in another constant. It then calls
 `replaceChildren()` on the list to transfer the options to, using the spread
 operator to pass in all the options contained in both constants.

```js
const noSelect = document.getElementById("no");
const yesSelect = document.getElementById("yes");
const noBtn = document.getElementById("to-no");
const yesBtn = document.getElementById("to-yes");

yesBtn.addEventListener("click", () => {
  const selectedTransferOptions =
    document.querySelectorAll("#no option:checked");
  const existingYesOptions = document.querySelectorAll("#yes option");
  yesSelect.replaceChildren(...selectedTransferOptions, ...existingYesOptions);
});

noBtn.addEventListener("click", () => {
  const selectedTransferOptions = document.querySelectorAll(
    "#yes option:checked",
  );
  const existingNoOptions = document.querySelectorAll("#no option");
  noSelect.replaceChildren(...selectedTransferOptions, ...existingNoOptions);
});
```

The end result looks like this:

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

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


Element: webkitmouseforcedown event - Web APIs

Element: webkitmouseforcedown event
===================================

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

After a `mousedown` event has been fired at the element, if and when sufficient pressure has been applied to the mouse or trackpad button to qualify as a "force click," Safari begins sending **`webkitmouseforcedown`** events to the element.

**`webkitmouseforcedown`** is a proprietary, WebKit-specific event. It is part of the `Force Touch Events` feature.

Syntax
------

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

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

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

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

A `MouseEvent`. Inherits from `UIEvent` and `Event`.

Event

UIEvent

MouseEventEvent properties
----------------

*This interface also inherits properties of its parents, `UIEvent` and `Event`.*

`MouseEvent.altKey` Read only

Returns `true` if the `alt` key was down when the mouse event was fired.

`MouseEvent.button` Read only

The button number that was pressed (if applicable) when the mouse event was fired.

`MouseEvent.buttons` Read only

The buttons being pressed (if any) when the mouse event was fired.

`MouseEvent.clientX` Read only

The X coordinate of the mouse pointer in viewport coordinates.

`MouseEvent.clientY` Read only

The Y coordinate of the mouse pointer in viewport coordinates.

`MouseEvent.ctrlKey` Read only

Returns `true` if the `control` key was down when the mouse event was fired.

`MouseEvent.layerX`
Non-standard
 Read only

Returns the horizontal coordinate of the event relative to the current layer.

`MouseEvent.layerY`
Non-standard
 Read only

Returns the vertical coordinate of the event relative to the current layer.

`MouseEvent.metaKey` Read only

Returns `true` if the `meta` key was down when the mouse event was fired.

`MouseEvent.movementX` Read only

The X coordinate of the mouse pointer relative to the position of the last `mousemove` event.

`MouseEvent.movementY` Read only

The Y coordinate of the mouse pointer relative to the position of the last `mousemove` event.

`MouseEvent.offsetX` Read only

The X coordinate of the mouse pointer relative to the position of the padding edge of the target node.

`MouseEvent.offsetY` Read only

The Y coordinate of the mouse pointer relative to the position of the padding edge of the target node.

`MouseEvent.pageX` Read only

The X coordinate of the mouse pointer relative to the whole document.

`MouseEvent.pageY` Read only

The Y coordinate of the mouse pointer relative to the whole document.

`MouseEvent.relatedTarget` Read only

The secondary target for the event, if there is one.

`MouseEvent.screenX` Read only

The X coordinate of the mouse pointer in screen coordinates.

`MouseEvent.screenY` Read only

The Y coordinate of the mouse pointer in screen coordinates.

`MouseEvent.shiftKey` Read only

Returns `true` if the `shift` key was down when the mouse event was fired.

`MouseEvent.mozInputSource`
Non-standard
 Read only

 The type of device that generated the event (one of the `MOZ_SOURCE_*` constants).
 This lets you, for example, determine whether a mouse event was generated by an actual mouse or by a touch event (which might affect the degree of accuracy with which you interpret the coordinates associated with the event).

`MouseEvent.webkitForce`
Non-standard
 Read only

The amount of pressure applied when clicking.

`MouseEvent.x` Read only

Alias for `MouseEvent.clientX`.

`MouseEvent.y` Read only

Alias for `MouseEvent.clientY`.

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

*Not part of any specification.* Apple has a description at the Mac Developer Library.

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

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

See also
--------

* Introduction to events
* `webkitmouseforcewillbegin`
* `webkitmouseforceup`
* `webkitmouseforcechanged`


Element: elementTiming property - Web APIs

Element: elementTiming property
===============================

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

The **`elementTiming`** property of the `Element` interface identifies elements for observation in the `PerformanceElementTiming` API. The `elementTiming` property reflects the value of the `elementtiming` attribute.

Value
-----

A string.

Examples
--------

### Logging the value of `elementTiming`

In this example, adding the `elementtiming` attribute to the `<img>` element sets the image to be observed.

```html
<img
 src="image.jpg"
 alt="a nice image"
 elementtiming="big-image"
 id="myImage" />
```

You can get the string value of the `elementtiming` HTML attribute by calling `el.elementTiming`.

```js
const el = document.getElementById("myImage");
console.log(el.elementTiming); // "big-image"
```

For a more complete example on how to use the Element Timing API, see `PerformanceElementTiming`.

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

| Specification |
| --- |
| Element Timing API # dom-element-elementtiming |

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

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

See also
--------

* `PerformanceElementTiming`
* `elementtiming` HTML attribute


Element: attachShadow() method - Web APIs

Element: attachShadow() method
==============================

Baseline Widely available
-------------------------

This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.

* Learn more
* See full compatibility
* Report feedback
The **`Element.attachShadow()`** method attaches a shadow DOM tree to the specified element and returns a reference to its `ShadowRoot`.

Elements you can attach a shadow to
-----------------------------------

 Note that you can't attach a shadow root to every type of element.
 There are some that can't have a shadow DOM for security reasons (for example `<a>`).

The following is a list of elements you *can* attach a shadow root to:

* Any autonomous custom element with a valid name
* `<article>`
* `<aside>`
* `<blockquote>`
* `<body>`
* `<div>`
* `<footer>`
* h1
* h2
* h3
* h4
* h5
* h6
* `<header>`
* `<main>`
* `<nav>`
* `<p>`
* `<section>`
* `<span>`
Syntax
------

```js
attachShadow(options)
```

### Parameters

`options`

An object which contains the following fields:

`mode`

 A string specifying the *encapsulation mode* for the shadow DOM tree.
 This can be one of:

`open`

 Elements of the shadow root are accessible from JavaScript outside the root,
 for example using `Element.shadowRoot`:

```js
element.attachShadow({ mode: "open" });
element.shadowRoot; // Returns a ShadowRoot obj
```

`closed`

 Denies access to the node(s) of a closed shadow root
 from JavaScript outside it:

```js
element.attachShadow({ mode: "closed" });
element.shadowRoot; // Returns null
```

`clonable` Optional

A boolean that specifies whether the shadow root is clonable: when set to `true`, the shadow host cloned with `Node.cloneNode()` or `Document.importNode()` will include shadow root in the copy. Its default value is `false`, unless the shadow root is created via declarative shadow DOM.

`delegatesFocus` Optional

 A boolean that, when set to `true`, specifies behavior that mitigates custom element issues around focusability.
 When a non-focusable part of the shadow DOM is clicked, the first focusable part is given focus, and the shadow host is given any available `:focus` styling. Its default value is `false`.

`slotAssignment` Optional

A string specifying the *slot assignment mode* for the shadow DOM tree. This can be one of:

`named`

Elements are automatically assigned to `<slot>` elements within this shadow root. Any descendants of the host with a `slot` attribute which matches the `name` attribute of a `<slot>` within this shadow root will be assigned to that slot. Any top-level children of the host with no `slot` attribute will be assigned to a `<slot>` with no `name` attribute (the "default slot") if one is present.

`manual`

 Elements are not automatically assigned to `<slot>` elements. Instead, they must be manually assigned with `HTMLSlotElement.assign()`.
 Its default value is `named`.

### Return value

Returns a `ShadowRoot` object.

### Exceptions

`InvalidStateError` `DOMException`

The element you are trying to attach to is already a shadow host.

`NotSupportedError` `DOMException`

 You are trying to attach a shadow root to an element outside the HTML namespace, the element cannot have a shadow attached to it,
 or the static property `disabledFeatures` has been given a value of `"shadow"` in the element definition.

Examples
--------

 The following example is taken from our word-count-web-component demo (see it live also).
 You can see that we use `attachShadow()` in the middle of the code to create a shadow root, which we then attach our custom element's contents to.

```js
// Create a class for the element
class WordCount extends HTMLParagraphElement {
  constructor() {
    // Always call super first in constructor
    super();

    // count words in element's parent element
    const wcParent = this.parentNode;

    function countWords(node) {
      const text = node.innerText || node.textContent;
      return text
        .trim()
        .split(/\s+/g)
        .filter((a) => a.trim().length > 0).length;
    }

    const count = `Words: ${countWords(wcParent)}`;

    // Create a shadow root
    const shadow = this.attachShadow({ mode: "open" });

    // Create text node and add word count to it
    const text = document.createElement("span");
    text.textContent = count;

    // Append it to the shadow root
    shadow.appendChild(text);

    // Update count when element content changes
    setInterval(() => {
      const count = `Words: ${countWords(wcParent)}`;
      text.textContent = count;
    }, 200);
  }
}

// Define the new element
customElements.define("word-count", WordCount, { extends: "p" });
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-element-attachshadow① |

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

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

See also
--------

* `ShadowRoot.mode`
* `ShadowRoot.delegatesFocus`
* `ShadowRoot.slotAssignment`


Element: ariaPlaceholder property - Web APIs

Element: ariaPlaceholder property
=================================

The **`ariaPlaceholder`** property of the `Element` interface reflects the value of the `aria-placeholder` attribute, which defines a short hint intended to aid the user with data entry when the control has no value.

**Note:** Where possible use an HTML `<input>` element with `type="text"` or a `<textarea>` as these have built in semantics and do not require ARIA attributes.

Value
-----

A string.

Examples
--------

In this example the `aria-placeholder` attribute on the element with an ID of `txtBoxInput` has been set to a string. Using `ariaPlaceholder` we update the string to another value.

```html
<div id="txtboxLabel">Enter your five-digit zipcode</div>
<div
 role="textbox"
 id="txtBoxInput"
 contenteditable="true"
 aria-placeholder="5-digit zipcode"
 aria-labelledby="txtboxLabel"></div>
```

```js
let el = document.getElementById("txtBoxInput");
console.log(el.ariaPlaceholder); // "5-digit zipcode"
el.ariaPlaceholder = "12345";
console.log(el.ariaPlaceholder); // "12345"
```

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

| Specification |
| --- |
| Accessible Rich Internet Applications (WAI-ARIA) # dom-ariamixin-ariaplaceholder |

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

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

See also
--------

* ARIA: textbox role