Is there a way to get the bounding rect of a text node?
The getBoundingClientRect() method is defined on elements only, and the parent element is bigger then the actual text node.
The getBoundingClientRect() method returns the size of an element and its position relative to the viewport. The getBoundingClientRect() method returns a DOMRect object with eight properties: left, top, right, bottom, x, y, width, height.
getBoundingClientRect() gives a result relative to the viewport's top-left corner ( 0,0 ), not relative to an element's parent, whereas el.
A text node encapsulates XML character content. A text node can have zero or one parent. The content of a text node can be empty. However, unless the parent of a text node is empty, the content of the text node cannot be an empty string.
Border, padding and margin are not included.
If you don't need to support IE8 or older, you can use a Range
to select the text node, and then get the bounding rect directly from the Range
.
Example (should work in this page):
var text = document.querySelector('#question-header .question-hyperlink').childNodes[0];
var range = document.createRange();
range.selectNode(text);
var rect = range.getBoundingClientRect();
range.detach(); // frees up memory in older browsers
You can also reuse the Range
object if you're doing this for multiple text nodes; just make sure not to call range.detach()
until you're done. (Note: Range.detach()
is now a no-op in the DOM standard, though some older browsers will still disable use of the range after its invocation.)
Wrap the text node in a <span>
, get the boundingRect
of that span.
var span = document.createElement('span');
textNode.parentNode.insertBefore(span, textNode);
span.appendChild(textNode);
var rect = span.getBoundingClientRect();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With