recursal/MDN huggingface dataset:
Selection: getRangeAt() method
==============================

 The **`Selection.getRangeAt()`** method returns a range object
 representing one of the ranges currently selected.

Syntax
------


```js
getRangeAt(index)
```

### Parameters

`index`

 The zero-based index of the range to return. A negative number or a number greater
 than or equal to `Selection.rangeCount` will result in an error.


### Return value

The specified `Range` object.

Examples
--------


```js
let ranges = [];

sel = window.getSelection();

for (let i = 0; i < sel.rangeCount; i++) {
  ranges[i] = sel.getRangeAt(i);
}
/\* Each item in the ranges array is now
 \* a range object representing one of the
 \* ranges in the current selection \*/
```

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

| Specification |
| --- |
| Selection API # dom-selection-getrangeat |

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

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

See also
--------

* `Selection`, the interface it belongs to.
Selection: extend() method
==========================

 The **`Selection.extend()`** method moves the focus of the
 selection to a specified point. The anchor of the selection does not move. The selection
 will be from the anchor to the new focus, regardless of direction.

Syntax
------


```js
extend(node)
extend(node, offset)
```

### Parameters

`node`

The node within which the focus will be moved.

`offset` Optional

 The offset position within `node` where the focus will be moved to. If
 not specified, the default value `0` is used.


### Return value

None (`undefined`).

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

| Specification |
| --- |
| Selection API # dom-selection-extend |

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

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

See also
--------

* `Selection`, the interface it belongs to.
Selection: removeRange() method
===============================

 The **`Selection.removeRange()`** method removes a range from a
 selection.

Syntax
------


```js
removeRange(range)
```

### Parameters

`range`

A range object that will be removed to the selection.

### Return value

None (`undefined`).

Examples
--------


```js
/\* Programmatically, more than one range can be selected.
 \* This will remove all ranges except the first. \*/
const s = window.getSelection();
if (s.rangeCount > 1) {
  for (let i = 1; i < s.rangeCount; i++) {
    s.removeRange(s.getRangeAt(i));
  }
}
```

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

| Specification |
| --- |
| Selection API # dom-selection-removerange |

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

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

See also
--------

* `Selection`, the interface it belongs to.
Selection: anchorOffset property
================================

 The **`Selection.anchorOffset`** read-only property returns the
 number of characters that the selection's anchor is offset within the
 `Selection.anchorNode`.

 This number is zero-based. If the selection begins with the first character in the
 `Selection.anchorNode`, `0` is returned.

Value
-----

A number.

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

| Specification |
| --- |
| Selection API # dom-selection-anchoroffset |

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

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

See also
--------

* `Selection`, the interface it belongs to.
Selection: focusNode property
=============================

 The **`Selection.focusNode`** read-only property returns the
 `Node` in which the selection ends.

 A user may make a selection from left to right (in document order) or right to left
 (reverse of document order). The focus is where the user ended the selection. This can
 be visualized by holding the `Shift` key and pressing the arrow keys on your
 keyboard to modify the current selection. The selection's focus moves, but the
 selection's anchor, the other end of the selection, does not move.

Value
-----

A `Node` object.

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

| Specification |
| --- |
| Selection API # dom-selection-focusnode |

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

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

See also
--------

* `Selection`, the interface it belongs to.
Selection: selectAllChildren() method
=====================================

 The **`Selection.selectAllChildren()`** method adds all the
 children of the specified node to the selection. Previous selection is lost.

Syntax
------


```js
selectAllChildren(parentNode)
```

### Parameters

`parentNode`

 All children of `parentNode` will be selected. `parentNode`
 itself is not part of the selection.


### Return value

None (`undefined`).

Examples
--------

### HTML


```html
<main>
  <button>Select Footer</button>
  <p>Welcome to my website.</p>
  <p>I hope you enjoy your visit.</p>
</main>
<footer>
  <address>webmaster@example.com</address>
  <p>© 2019</p>
</footer>
```

### JavaScript


```js
const button = document.querySelector("button");
const footer = document.querySelector("footer");

button.addEventListener("click", (e) => {
  window.getSelection().selectAllChildren(footer);
});
```

### Result

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

| Specification |
| --- |
| Selection API # dom-selection-selectallchildren |

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

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

See also
--------

* `Selection`, the interface it belongs to.
Selection: collapseToEnd() method
=================================

 The **`Selection.collapseToEnd()`** method collapses the
 selection to the end of the last range in the selection. If the content of the selection
 is focused and editable, the caret will blink there.

Syntax
------


```js
collapseToEnd()
```

### Parameters

None.

### Return value

None (`undefined`).

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

| Specification |
| --- |
| Selection API # dom-selection-collapsetoend |

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

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

See also
--------

* `Selection`, the interface it belongs to.
Selection: empty() method
=========================

The **`Selection.empty()`** method removes all ranges from the selection, leaving the `anchorNode` and `focusNode` properties equal to `null` and nothing selected. When this method is called, a `selectionchange` event is fired at the document.

**Note:** This method is an alias for the `Selection.removeAllRanges()` method.

Syntax
------


```js
empty()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

This example displays a message when something is selected on the page or not. It does this by listening to the `selectionchange` event on the document. There also is a button that clears any selection by calling `Selection.empty()`. When this happens, the selection is changed and the message is updated.


```html
<p>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse laoreet
  urna eget sapien venenatis, eget facilisis diam mattis.
</p>
<button>Clear selection</button>
<pre id="log"></pre>
```



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

// The selection object is a singleton associated with the document
const selection = document.getSelection();

// Logs if there is a selection or not
function newSelectionHandler() {
  if (selection.rangeCount !== 0) {
    log.textContent = "Some text is selected.";
  } else {
    log.textContent = "No selection on this document.";
  }
}

document.addEventListener("selectionchange", () => {
  newSelectionHandler();
});

newSelectionHandler();

// The button cancel all selection ranges
const button = document.querySelector("button");
button.addEventListener("click", () => {
  selection.empty();
});
```

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

| Specification |
| --- |
| Selection API # dom-selection-removeallranges |

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

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

See also
--------

* `Selection.removeAllRanges()`
* `selectionchange`
Selection: anchorNode property
==============================

 The **`Selection.anchorNode`** read-only property returns the
 `Node` in which the selection begins.

 A user may make a selection from left to right (in document order) or right to left
 (reverse of document order). The anchor is where the user began the selection. This can
 be visualized by holding the Shift key and pressing the arrow keys on your keyboard. The
 selection's anchor does not move, but the selection's focus, the other end of the
 selection, does move.

Value
-----

A `Node` object.

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

| Specification |
| --- |
| Selection API # dom-selection-anchornode |

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

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

See also
--------

* `Selection`, the interface it belongs to.
Selection: isCollapsed property
===============================

 The **`Selection.isCollapsed`** read-only property returns a
 boolean value which indicates whether or not there is currently any text
 selected. No text is selected when the selection's start and end points are at the same
 position in the content.

 Keep in mind that a collapsed selection may still have one (or more, in Gecko)
 `Range`s, so `Selection.rangeCount` may not be zero. In that
 scenario, calling a `Selection` object's `getRangeAt()` method may return a `Range` object which is collapsed.

Value
-----

A boolean.

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

| Specification |
| --- |
| Selection API # dom-selection-iscollapsed |

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

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

See also
--------

* `Selection`
* `Range`
Selection: addRange() method
============================

 The **`Selection.addRange()`** method adds a
 `Range` to a `Selection`.

Syntax
------


```js
addRange(range)
```

### Parameters

`range`

A `Range` object that will be added to the `Selection`.

### Return value

None (`undefined`).

Examples
--------

**Note:** Currently only Firefox supports multiple selection ranges, other browsers will not
 add new ranges to the selection if it already contains one.


### HTML


```html
<p>
  I <strong>insist</strong> that you <strong>try</strong> selecting the
  <strong>strong words</strong>.
</p>
<button>Select strong words</button>
```

### JavaScript


```js
let button = document.querySelector("button");

button.addEventListener("click", () => {
  const selection = window.getSelection();
  const strongs = document.getElementsByTagName("strong");

  if (selection.rangeCount > 0) {
    selection.removeAllRanges();
  }

  for (const node of strongs) {
    const range = document.createRange();
    range.selectNode(node);
    selection.addRange(range);
  }
});
```

### Result

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

| Specification |
| --- |
| Selection API # dom-selection-addrange |

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

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

See also
--------

* `Selection`, the interface this method belongs to
Selection: removeAllRanges() method
===================================

The **`Selection.removeAllRanges()`** method removes all ranges from the selection, leaving the `anchorNode` and `focusNode` properties equal to `null` and nothing selected. When this method is called, a `selectionchange` event is fired at the document.

**Note:** This method is an alias for the `Selection.empty()` method.

Syntax
------


```js
removeAllRanges()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

This example displays a message when something is selected on the page or not. It does this by listening to the `selectionchange` event on the document. There also is a button that clears any selection by calling `Selection.removeAllRanges()`. When this happens, the selection is changed and the message is updated.


```html
<p>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse laoreet
  urna eget sapien venenatis, eget facilisis diam mattis.
</p>
<button>Clear selection</button>
<pre id="log"></pre>
```



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

// The selection object is a singleton associated with the document
const selection = document.getSelection();

// Logs if there is a selection or not
function newSelectionHandler() {
  if (selection.rangeCount !== 0) {
    log.textContent = "Some text is selected.";
  } else {
    log.textContent = "No selection on this document.";
  }
}

document.addEventListener("selectionchange", () => {
  newSelectionHandler();
});

newSelectionHandler();

// The button cancel all selection ranges
const button = document.querySelector("button");
button.addEventListener("click", () => {
  selection.removeAllRanges();
});
```

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

| Specification |
| --- |
| Selection API # dom-selection-removeallranges |

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

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

See also
--------

* `Selection.empty()`
* `selectionchange`
Selection: deleteFromDocument() method
======================================

 The **`deleteFromDocument()`** method of the
 `Selection` interface deletes the selected text from the document's DOM.

Syntax
------


```js
deleteFromDocument()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

 This example lets you delete selected text by clicking a button. Upon clicking the
 button, the
 `Window.getSelection()` method gets the selected text, and the
 `deleteFromDocument()` method removes it.

### HTML


```html
<p>
  Try highlighting some of the text in this paragraph. Once you do, you can
  remove the selected content by clicking the button below.
</p>
<button>Delete selected text</button>
```

### JavaScript


```js
let button = document.querySelector("button");
button.addEventListener("click", deleteSelection);

function deleteSelection() {
  let selection = window.getSelection();
  selection.deleteFromDocument();
}
```

### Result

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

| Specification |
| --- |
| Selection API # dom-selection-deletefromdocument |

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

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

See also
--------

* `Selection`, the interface defining this method
Selection: collapseToStart() method
===================================

 The **`Selection.collapseToStart()`** method collapses the
 selection to the start of the first range in the selection. If the content of the
 selection is focused and editable, the caret will blink there.

Syntax
------


```js
collapseToStart()
```

### Parameters

None.

### Return value

None (`undefined`).

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

| Specification |
| --- |
| Selection API # dom-selection-collapsetostart |

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

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

See also
--------

* `Selection`, the interface it belongs to.
MutationRecord: oldValue property
=================================

The `MutationRecord` read-only property **`oldValue`** contains the character data or attribute value of an observed node before it was changed.

Value
-----

A string representing the old value of an attribute which has been changed, if:

* the `attributeOldValue` parameter to `MutationObserver.observe()` is `true`
* the `attributes` parameter to `MutationObserver.observe()` is `true` or omitted
* the mutation `type` is `attributes`.

A string representing the old value of a `CharacterData` node that has been changed, if:

* the `characterDataOldValue` parameter to `MutationObserver.observe()` is `true`
* the `characterData` parameter to `MutationObserver.observe()` is `true` or omitted
* the mutation `type` is `characterData`.

Otherwise this property is `null`.

Examples
--------

### Show old color value

In the following example, there is a button that changes the color of an `h1` to a random new color. A `MutationObserver` is used to observe the target node (`h1`) for changes to the attribute; when a change is detected, the observer calls a function, `logOldValue()`.

The `logOldValue()` function is passed the `mutationRecords` array, which contains the `MutationRecord` objects. The `oldValue` property of the `MutationRecord` object is then displayed, in the color of the old value.

#### HTML


```html
<h1 id="h1" style="color: rgb(0 0 0);">Hi, Mom!</h1>
<button id="changeColorButton">Change color</button>
<p id="log"></p>
```


#### JavaScript


```js
const h1 = document.getElementById("h1");
const changeValueButton = document.getElementById("changeColorButton");
const log = document.getElementById("log");

changeColorButton.addEventListener("click", () => {
  // Random 6 character hexadecimal number to use as the hex color value
  const newColor = Math.floor(Math.random() \* 16777215).toString(16);
  h1.style.color = `#${newColor}`;
});

function logOldValue(mutationRecordArray) {
  for (const record of mutationRecordArray) {
    log.textContent = `Old value: ${record.oldValue}`;
    log.style.cssText = record.oldValue;
  }
}

const observer = new MutationObserver(logOldValue);
observer.observe(h1, {
  attributes: true,
  attributeOldValue: true,
});
```


#### Result

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-mutationrecord-oldvalue② |

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

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

The `MutationRecord` read-only property **`nextSibling`** is the next sibling of an added or removed child node of the `target` of a `MutationObserver`.

Value
-----

If a node is added to or removed from the `target` of a `MutationObserver`, the value is the `Node` that is the next sibling of the added or removed node: that is, the node immediately following this one in the parent's `childNodes` list.

The value is `null` if there are no added or removed nodes, or if the node is the last child of its parent.

Examples
--------

### Log the next sibling of a mutation

This adds a node every time you click the button, but it adds the node at the *start of the target*, not the end. Then the observer logs the `textContent` of the `nextSibling` of the added node.

#### HTML


```html
<button id="add-nodes">Add a node</button>
<button id="reset">Reset</button>

<pre id="log" class="log">Next sibling of added node:</pre>
<div id="target"><p>Node #0</p></div>
```


```
.log {
  border: 1px dotted black;
  padding: 0.5rem;
}
```


#### JavaScript


```js
const addNodes = document.querySelector("#add-nodes");
const reset = document.querySelector("#reset");
const target = document.querySelector("#target");
let nodeNumber = 1;

addNodes.addEventListener("click", () => {
  const newPara = document.createElement("p");
  newPara.textContent = `Node #${nodeNumber}`;
  nodeNumber++;
  target.insertBefore(newPara, target.firstChild);
});

reset.addEventListener("click", () => self.location.reload());

function logNextSibling(records) {
  for (const record of records) {
    if (record.type === "childList") {
      for (const newNode of record.addedNodes) {
        log.textContent = `Next sibling of added node: ${record.nextSibling?.textContent}`;
      }
    }
  }
}

const observer = new MutationObserver(logNextSibling);
observer.observe(target, { childList: true });
```


#### Result

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-mutationrecord-nextsibling② |

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

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

The `MutationRecord` read-only property **`addedNodes`** is a `NodeList` of nodes added to a target node by a mutation observed with a `MutationObserver`.

Value
-----

A `NodeList` containing the nodes added to the target of the mutation observed by the `MutationObserver`.

Examples
--------

### Update when adding a node

In the following example, there are two buttons: one to add new nodes to a target node, and one to remove them. A `MutationObserver` is used to observe the target node for changes; when a change is detected, the observer calls a function, `logNewNodes()`.

The `logNewNodes()` function checks that the MutationRecord's `type` is `childList`, which means that the target node's children have changed. If the type is `childlist` the function updates the total number of new nodes that have been added. However, note that clicking the "Remove a node" button will not increment the total number of new nodes, because in this case `record.addedNodes` will have a length of `0`.

#### HTML


```html
<button id="add-nodes">Add a node</button>
<button id="remove-nodes">Remove a node</button>
<button id="reset">Reset</button>

<pre id="counter">Total added nodes: 0</pre>
<div id="target"></div>
```


```
#counter {
  border: 1px dotted black;
  padding: 0.5rem;
}
```


#### JavaScript


```js
const addNodes = document.querySelector("#add-nodes");
const removeNodes = document.querySelector("#remove-nodes");
const reset = document.querySelector("#reset");
const counter = document.querySelector("#counter");
const target = document.querySelector("#target");
let totalAddedNodes = 0;

addNodes.addEventListener("click", () => {
  const newPara = document.createElement("p");
  newPara.textContent = `Current time: ${Date.now()}`;
  target.appendChild(newPara);
});

removeNodes.addEventListener("click", () => {
  const lastChild = target.lastChild;
  if (lastChild) {
    target.removeChild(lastChild);
  }
});

reset.addEventListener("click", () => self.location.reload());

function logNewNodes(records) {
  for (const record of records) {
    // Check if the childlist of the target node has been mutated
    if (record.type === "childList") {
      totalAddedNodes = totalAddedNodes + record.addedNodes.length;
      // Log the number of nodes added
      counter.textContent = `Total added nodes: ${totalAddedNodes}`;
    }
  }
}

const observer = new MutationObserver(logNewNodes);
observer.observe(target, { childList: true });
```


#### Result

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-mutationrecord-addednodes② |

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

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