Reputation: 165
Not sure how to word this question. What I want to do is get the positions of individual lines in an HTML text node.
For example, in this image, each blue box is a span
with some styling and padding. So the blue box with the text "test 3 testing hello test test test!" is a single span
that wraps onto the next line and it's HTML looks like this:
<span>test 3 testing hello test test test!</span>
How can I get the client top, left, width, and height for each of the two lines of text? That is, I'd like all the size/position information for just the "test 3 testing hello test" part of the line, as well as the size/position information for the "test test!" line. Relative to either the page or the parent div. If I call getBoundingClientRect()
on the span
itself, it gives me none of that information, just the combination of the first and second line, and as far as I can tell the text is not broken up into smaller nodes for me to iterate over in JS.
Upvotes: 1
Views: 1013
Reputation: 165
Found the answer after I gave up on this problem several months ago.
Apparently, you can call getBoundingClientRect()
on a Range
. This will give you the bounding rect of the selected text.
If greater detail is needed, down the the individual lines of the text, then you should call getClientRects()
on the Range
, which will return a rect for each line of text in the selected range.
const el = document.querySelector("#my-element");
const range = document.createRange();
range.setStart(el, 0);
range.setEnd(el, 200);
// A single rect for the entire range
const rect = range.getBoundingClientRect();
// An array of rects for each line of the range
const rects = range.getClientRects();
Although it's considered an experimental API by MDN, both functions are supported by all major browsers:
https://developer.mozilla.org/en-US/docs/Web/API/Range/getBoundingClientRect https://developer.mozilla.org/en-US/docs/Web/API/Range/getClientRects
Upvotes: 5
Reputation: 142
The method elem.getBoundingClientRect()
returns window coordinates for a minimal rectangle that encloses elem as an object of built-in DOMRect class.
Main DOMRect properties:
x/y
– X/Y-coordinates of the rectangle origin relative to window,
width/height
– width/height of the rectangle (can be negative).
Additionally, there are derived properties:
top/bottom
– Y-coordinate for the top/bottom rectangle edge,
left/right
– X-coordinate for the left/right rectangle edge.
Document coordinates:
// get document coordinates of the element
function getCoords(elem) {
let box = elem.getBoundingClientRect();
return {
top: box.top + window.pageYOffset,
right: box.right + window.pageXOffset,
bottom: box.bottom + window.pageYOffset,
left: box.left + window.pageXOffset
};
}
Upvotes: 0