This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
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.
getBoundingClientRect()
None.
A DOMRect object that encloses the union of the bounding rectangles for all elements in the range.
<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>
#highlight {
background: yellow;
position: absolute;
z-index: -1;
}
p {
width: 200px;
}
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`;
| Specification |
|---|
| CSSOM View Module> # dom-range-getboundingclientrect> |
| Desktop | Mobile | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Opera | Safari | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | WebView Android | WebView on iOS | |
getBoundingClientRect |
4 | 12 | 4 | ≤12.1 | 5 | 18 | 4 | ≤12.1 | 4 | 1.0 | 4.4 | 4 |
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.
© 2005–2025 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Range/getBoundingClientRect