recursal/MDN huggingface dataset:
Range: compareBoundaryPoints() method
=====================================

 The
 **`Range.compareBoundaryPoints()`** method compares the
 boundary points of the `Range` with those of another range.

Syntax
------


```js
compareBoundaryPoints(how, sourceRange)
```

### Parameters

`how`

A constant describing the comparison method:

* `Range.END_TO_END` compares the end boundary-point of
 *sourceRange* to the end boundary-point of `Range`.
* `Range.END_TO_START` compares the end boundary-point of
 *sourceRange* to the start boundary-point of `Range`.
* `Range.START_TO_END` compares the start boundary-point of
 *sourceRange* to the end boundary-point of `Range`.
* `Range.START_TO_START` compares the start boundary-point of
 *sourceRange* to the start boundary-point of `Range`.

`sourceRange`

A `Range` to compare boundary points with the range.

### Return value

 A number, `-1`, `0`, or `1`, indicating whether the
 corresponding boundary-point of the `Range` is respectively before, equal
 to, or after the corresponding boundary-point of *sourceRange*.

### Exceptions

`NotSupportedError` `DOMException`

Thrown if the value of the `how` parameter is invalid.

Examples
--------


```js
const range = document.createRange();
range.selectNode(document.querySelector("div"));
const sourceRange = document.createRange();
sourceRange.selectNode(document.getElementsByTagName("div")[1]);
const compare = range.compareBoundaryPoints(Range.START\_TO\_END, sourceRange);
```

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

| Specification |
| --- |
| DOM Standard # dom-range-compareboundarypoints |

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

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

See also
--------

* The DOM interfaces index
Range: selectNode() method
==========================

 The **`Range.selectNode()`** method sets the
 `Range` to contain the `Node` and its contents. The parent
 `Node` of the start and end of the `Range` will be the same as
 the parent of the *referenceNode*.

Syntax
------


```js
selectNode(referenceNode)
```

### Parameters

`referenceNode`

The `Node` to select within a `Range`.

### Return value

None (`undefined`).

Examples
--------


```js
let range = document.createRange();
let referenceNode = document.getElementsByTagName("div").item(0);

range.selectNode(referenceNode);
```

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

| Specification |
| --- |
| DOM Standard # dom-range-selectnode |

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

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

See also
--------

* The DOM interfaces index
Range: extractContents() method
===============================

 The **`Range.extractContents()`** method moves contents of the
 `Range` from the document tree into a `DocumentFragment`.

 Event listeners added using DOM Events are not retained during extraction. HTML
 attribute events are retained or duplicated as they are for the
 `Node.cloneNode()` method. HTML `id` attributes are also cloned,
 which can lead to an invalid document if a partially-selected node is extracted and
 appended to the document.

 Partially selected nodes are cloned to include the parent tags necessary to make the
 document fragment valid.

Syntax
------


```js
extractContents()
```

### Parameters

None.

### Return value

A `DocumentFragment` object.

Examples
--------

### Basic example


```js
const range = document.createRange();
range.selectNode(document.getElementsByTagName("div").item(0));
const documentFragment = range.extractContents();
document.body.appendChild(documentFragment);
```

### Moving items between containers

 This example lets you move items between two containers. Select one or more item, and
 then click "swap" to move them to the opposite container.

#### HTML


```html
<p id="list1">123456</p>
<button id="swap">Swap selected item(s)</button>
<p id="list2">abcdef</p>
```


#### CSS


```css
body {
  pointer-events: none;
}

p {
  border: 1px solid;
  font-size: 2em;
  padding: 0.3em;
}

button {
  font-size: 1.2em;
  padding: 0.5em;
  pointer-events: auto;
}
```


#### JavaScript


```js
const list1 = document.getElementById("list1");
const list2 = document.getElementById("list2");
const button = document.getElementById("swap");

button.addEventListener("click", (e) => {
  selection = window.getSelection();

  for (let i = 0; i < selection.rangeCount; i++) {
    const range = selection.getRangeAt(i);

    if (
      range.commonAncestorContainer === list1 ||
      range.commonAncestorContainer.parentNode === list1
    ) {
      const documentFragment = range.extractContents();
      list2.appendChild(documentFragment);
    } else if (
      range.commonAncestorContainer === list2 ||
      range.commonAncestorContainer.parentNode === list2
    ) {
      const documentFragment = range.extractContents();
      list1.appendChild(documentFragment);
    }
  }
});
```


#### Result

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

| Specification |
| --- |
| DOM Standard # dom-range-extractcontents |

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

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

See also
--------

* The DOM interfaces index
Range: surroundContents() method
================================

 The **`Range.surroundContents()`** method moves content of the
 `Range` into a new node, placing the new node at the start of the
 specified range.

 This method is nearly equivalent to
 `newNode.appendChild(range.extractContents()); range.insertNode(newNode)`.
 After surrounding, the boundary points of the `range` include
 `newNode`.

 An exception will be thrown, however, if the `Range` splits a non-`Text` node with only one of its boundary points. That is, unlike the
 alternative above, if there are partially selected nodes, they will not be cloned and
 instead the operation will fail.

Syntax
------


```js
surroundContents(newParent)
```

### Parameters

`newParent`

A `Node` with which to surround the contents.

### Return value

None (`undefined`).

Examples
--------

### HTML


```html
<span class="header-text">Put this in a headline</span>
```

### JavaScript


```js
const range = document.createRange();
const newParent = document.createElement("h1");

range.selectNode(document.querySelector(".header-text"));
range.surroundContents(newParent);
```

### Result

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

| Specification |
| --- |
| DOM Standard # dom-range-surroundcontents |

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

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

See also
--------

* The DOM interfaces index
Range: intersectsNode() method
==============================

 The **`Range.intersectsNode()`** method returns a boolean
 indicating whether the given `Node` intersects the `Range`.

Syntax
------


```js
intersectsNode(referenceNode)
```

### Parameters

`referenceNode`

The `Node` to compare with the `Range`.

### Return value

A boolean.

Examples
--------


```js
const range = document.createRange();

range.selectNode(document.getElementsByTagName("div").item(0));
const intersectingNode = range.intersectsNode(
  document.getElementsByTagName("p").item(0),
);
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-range-intersectsnode① |

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

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

See also
--------

* The DOM interfaces index
Range: startOffset property
===========================

 The **`Range.startOffset`** read-only property returns a number
 representing where in the `startContainer` the `Range` starts.

 If the `startContainer` is a `Node` of type
 `Text`, `Comment`, or `CDATASection`, then the
 offset is the number of characters from the start of the `startContainer` to
 the boundary point of the `Range`. For other `Node` types, the
 `startOffset` is the number of child nodes between the start of the
 `startContainer` and the boundary point of the `Range`.

 To change the `startOffset` of a `Range`, use the
 `Range.setStart` method.

Value
-----

A number.

Examples
--------


```js
const range = document.createRange();
range.setStart(startNode, startOffset);
range.setEnd(endNode, endOffset);
const startRangeOffset = range.startOffset;
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-range-startoffset① |

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

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

See also
--------

* The DOM interfaces index
Range: collapse() method
========================

 The **`Range.collapse()`** method collapses the
 `Range` to one of its boundary points.

 A collapsed `Range` is empty, containing no content, specifying a
 single-point in a DOM tree. To determine if a `Range` is already collapsed,
 see the `Range.collapsed` property.

Syntax
------


```js
collapse()
collapse(toStart)
```

### Parameters

`toStart` Optional

 A boolean value: `true` collapses the `Range`
 to its start, `false` to its end. If omitted, it defaults to
 `false` 
Experimental
.


### Return value

None (`undefined`).

Examples
--------


```js
const range = document.createRange();

const referenceNode = document.getElementsByTagName("div").item(0);
range.selectNode(referenceNode);
range.collapse(true);
```

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

| Specification |
| --- |
| DOM Standard # dom-range-collapse |

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

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

See also
--------

* The DOM interfaces index
Range: selectNodeContents() method
==================================

The **`Range.selectNodeContents()`** method sets the `Range` to contain the contents of a `Node`.

 The parent `Node` of the start and end of the `Range` will be the
 reference node. The `startOffset` is 0, and the `endOffset` is the
 number of child `Node`s or number of characters contained in the reference
 node.

Syntax
------


```js
selectNodeContents(referenceNode)
```

### Parameters

`referenceNode`

The `Node` whose contents will be selected within a `Range`.

### Return value

None (`undefined`).

Examples
--------


```js
const range = document.createRange();
const referenceNode = document.querySelector("div");
range.selectNodeContents(referenceNode);
```

### Live sample

 This example lets the user select and deselect a paragraph with buttons.
 `Document.createRange()`, `Range.selectNodeContents()`, and
 `Selection.addRange()` are used to select the content.
 `Window.getSelection()` and `Selection.removeAllRanges()` are
 used to deselect it.

#### HTML


```html
<p id="p">
  <strong>Use the buttons below</strong> to select or deselect the contents of
  this paragraph.
</p>
<button id="select-button">Select paragraph</button>
<button id="deselect-button">Deselect paragraph</button>
```


#### JavaScript


```js
const p = document.getElementById("p");
const selectButton = document.getElementById("select-button");
const deselectButton = document.getElementById("deselect-button");

selectButton.addEventListener("click", (e) => {
  // Clear any current selection
  const selection = window.getSelection();
  selection.removeAllRanges();

  // Select paragraph
  const range = document.createRange();
  range.selectNodeContents(p);
  selection.addRange(range);
});

deselectButton.addEventListener("click", (e) => {
  const selection = window.getSelection();
  selection.removeAllRanges();
});
```


#### Result

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

| Specification |
| --- |
| DOM Standard # dom-range-selectnodecontents |

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

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

See also
--------

* The DOM interfaces index
Range: setStart() method
========================

 The **`Range.setStart()`** method sets the start position of a
 `Range`.

 If the `startNode` is a `Node` of type `Text`,
 `Comment`, or `CDataSection`, then `startOffset` is
 the number of characters from the start of `startNode`. For other
 `Node` types, `startOffset` is the number of child nodes between
 the start of the `startNode`.

 Setting the start point below (lower in the document) the end point will result in a
 collapsed range with the start and end points both set to the specified start position.

Syntax
------


```js
setStart(startNode, startOffset)
```

### Parameters

`startNode`

The `Node` where the `Range` should start.

`startOffset`

 An integer greater than or equal to zero representing the offset for the start of
 the `Range` from the start of `startNode`.


### Return value

None (`undefined`).

Examples
--------

### Highlight part of an element

 This example uses the `Range.setStart()` and `Range.setEnd()`
 methods to add part of an address to a range. The selected range is then highlighted
 using `Range.surroundContents()`.

 The address contains nine nodes: five text nodes, and four `<br>`
 elements.

#### HTML


```html
<p id="address">
  Wyatt Earp<br />
  101 E. Main St.<br />
  Dodge City, KS<br />
  67801<br />
  USA
</p>

<hr />
<p>Nodes in the original address:</p>
<ol id="log"></ol>
```


#### JavaScript


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

// Log info
address.childNodes.forEach((node) => {
  const li = document.createElement("li");
  li.textContent = `${node.nodeName}, ${node.nodeValue}`;
  log.appendChild(li);
});

// Highlight the street and city
const startOffset = 2; // Start at third node: 101 E. Main St.
const endOffset = 5; // End at fifth node: Dodge City, KS
const range = document.createRange();
range.setStart(address, startOffset);
range.setEnd(address, endOffset);

const mark = document.createElement("mark");
range.surroundContents(mark);
```


#### Result

### Get characters from a text node

 This example uses the `Range.setStart()` and `Range.setEnd()`
 methods to define the contents of a range. The resulting range contains the first
 through fifth characters within a text node.

#### HTML


```html
<p id="content">0123456789</p>
<p id="log"></p>
```


#### JavaScript


```js
const element = document.getElementById("content");
const textNode = element.childNodes[0];
const range = document.createRange();
range.setStart(textNode, 0); // Start at first character
range.setEnd(textNode, 5); // End at fifth character
document.getElementById("log").textContent = range;
```


#### Result

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

| Specification |
| --- |
| DOM Standard # dom-range-setstart |

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

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

See also
--------

* The DOM interfaces index
Range: setStartAfter() method
=============================

 The **`Range.setStartAfter()`** method sets the start position
 of a `Range` relative to a `Node`. The parent
 `Node` of the start of the `Range` will be the same as that
 for the `referenceNode`.

Syntax
------


```js
setStartAfter(referenceNode)
```

### Parameters

`referenceNode`

The `Node` to start the `Range` after.

### Return value

None (`undefined`).

Examples
--------


```js
const range = document.createRange();
const referenceNode = document.getElementsByTagName("div").item(0);

range.setStartAfter(referenceNode);
```

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

| Specification |
| --- |
| DOM Standard # dom-range-setstartafter |

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

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

See also
--------

* The DOM interfaces index
Range: setEndBefore() method
============================

 The **`Range.setEndBefore()`** method sets the end position of
 a `Range` relative to another `Node`. The parent
 `Node` of end of the `Range` will be the same as that for the
 `referenceNode`.

Syntax
------


```js
setEndBefore(referenceNode)
```

### Parameters

`referenceNode`

The `Node` to end the `Range` before.

### Return value

None (`undefined`).

Examples
--------


```js
const range = document.createRange();
const referenceNode = document.getElementsByTagName("div").item(0);

range.setEndBefore(referenceNode);
```

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

| Specification |
| --- |
| DOM Standard # dom-range-setendbefore |

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

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

See also
--------

* The DOM interfaces index
Range: insertNode() method
==========================

 The **`Range.insertNode()`** method inserts a node at the start
 of the `Range`.

 The new node is inserted at the start boundary point of the `Range`. If the
 new node is to be added to a text `Node`, that `Node` is split
 at the insertion point, and the insertion occurs between the two text nodes.

 If the new node is a document fragment, the children of the document fragment are
 inserted instead.

Syntax
------


```js
insertNode(newNode)
```

### Parameters

`newNode`

The `Node` to insert at the start of the `range`.

### Return value

None (`undefined`).

Examples
--------


```js
range = document.createRange();
newNode = document.createElement("p");
newNode.appendChild(document.createTextNode("New Node Inserted Here"));
range.selectNode(document.getElementsByTagName("div").item(0));
range.insertNode(newNode);
```

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

| Specification |
| --- |
| DOM Standard # dom-range-insertnode |

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

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

See also
--------

* The DOM interfaces index
Range: setEnd() method
======================

 The **`Range.setEnd()`** method sets the end position of a `Range` to be located at the given offset into the specified node x.Setting
 the end point above (higher in the document) than the start point will result in a
 collapsed range with the start and end points both set to the specified end position.

Syntax
------


```js
setEnd(endNode, endOffset)
```

### Parameters

`endNode`

The `Node` inside which the `Range` should end.

`endOffset`

An integer greater than or equal to zero representing the offset for the end of the `Range` from the start of `endNode`.

### Return value

None (`undefined`).

### Exceptions

`InvalidNodeTypeError` `DOMException`

The node specified by `endNode` is a doctype node; range endpoints cannot be located inside a doctype node.

`IndexSizeError` `DOMException`

The value specified by `endOffset` is either greater than or equal to the length of the node or is less than zero.

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

 If the `endNode` is a `Node` of type `Text`,
 `Comment`, or `CDataSection`, then `endOffset` is
 the number of characters from the start of `endNode`. For other
 `Node` types, `endOffset` is the number of child nodes between
 the start of the `endNode`.

Examples
--------


```js
const range = document.createRange();
const endNode = document.getElementsByTagName("p").item(3);
const endOffset = endNode.childNodes.length;
range.setEnd(endNode, endOffset);
```


**Note:** `setEnd()` is commonly used in conjunction with
 `setStart()` to fully configure a range.


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

| Specification |
| --- |
| DOM Standard # dom-range-setend |

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

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

See also
--------

* The DOM interfaces index
Range: endOffset property
=========================

 The **`Range.endOffset`** read-only property returns a number
 representing where in the `Range.endContainer` the `Range`
 ends.

 If the `endContainer` is a `Node` of type `Text`,
 `Comment`, or `CDATASection`, then the offset is the number of
 characters from the start of the `endContainer` to the boundary point of the
 `Range`. For other `Node` types, the `endOffset` is
 the number of child nodes between the start of the `endContainer` and the
 boundary point of the `Range`. This property is read-only. To change the
 `endOffset` of a `Range`, use one of the
 `Range.setEnd` methods.

Value
-----

A number.

Examples
--------


```js
const range = document.createRange();

range.setStart(startNode, startOffset);
range.setEnd(endNode, endOffset);
endRangeOffset = range.endOffset;
```

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

| Specification |
| --- |
| DOM Standard # ref-for-dom-range-endoffset① |

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

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

See also
--------

* The DOM interfaces index
Range: getBoundingClientRect() method
=====================================

 The **`Range.getBoundingClientRect()`** method returns a `DOMRect` object that bounds the contents of the range; this is a rectangle
 enclosing the union of the bounding rectangles for all the elements in the range.

 This method is useful for determining the viewport coordinates of the cursor or
 selection inside a text box. See `Element.getBoundingClientRect()` for
 details on the returned value.

Syntax
------


```js
getBoundingClientRect()
```

### Parameters

None.

### Return value

A `DOMRect` object that encloses the union of the bounding rectangles for all elements in the range.

Examples
--------

### HTML


```html
<div id="highlight"></div>
<p>
  This example positions a "highlight" rectangle behind the contents of a range.
  The range's content <em>starts here</em> and continues on until it
  <em>ends here</em>. The bounding client rectangle contains everything selected
  in the range.
</p>
```

### CSS


```css
#highlight {
  background: yellow;
  position: absolute;
  z-index: -1;
}

p {
  width: 200px;
}
```

### JavaScript


```js
const range = document.createRange();
range.setStartBefore(document.getElementsByTagName("em").item(0));
range.setEndAfter(document.getElementsByTagName("em").item(1));

const clientRect = range.getBoundingClientRect();
const highlight = document.getElementById("highlight");
highlight.style.left = `${clientRect.x}px`;
highlight.style.top = `${clientRect.y}px`;
highlight.style.width = `${clientRect.width}px`;
highlight.style.height = `${clientRect.height}px`;
```

### Result

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

| Specification |
| --- |
| CSSOM View Module # dom-range-getboundingclientrect |

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

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

See also
--------

* `Range.getClientRects()` - finer-grained result for non-rectangular
 ranges (e.g., when the selection wraps onto the next line);
* `Element.getBoundingClientRect()`
* `Document.caretPositionFromPoint()` - to get the (node, offset) from
 viewport coordinates.